Dynamically render React components

Recently on my team, I was tasked with figuring out how to dynamically render React components from strings that represented the component names. For instance, given const str = "Hello"; I would have to render the <Hello/> component.

The reason we needed to do this was so that we could retrieve stored component names from a database and render them on the front-end. So, can it be done?

Yes it can be done! #

If you’re simply here to find the coded up solution, then I got you covered. You can find the code on this sandbox.

Explanation: #

There needs to be a mapping between strings and components. Though it looks a little strange, basically the “Hello” string is being mapped to the <Hello/> component.

import Hello from './Hello';

const components = {
      Hello: Hello

The next step involves creating a React element using the above components mapping. After we have created this React element (called dynamicComponent), we can simply insert the variable anywhere in our render() function. We can pass props using createElement’s API. Notice here, the props are the object { name: 'Shahz' }.

const component_string = 'Hello';
const ComponentName = this.state.components[component_string];
const dynamicComponent = React.createElement(ComponentName, { name: 'Shahz' }, null);
render() {

Once again, you can find the code on this sandbox.


Now read this

Deep learning AWS EC2 set up

This is an accompanying blogpost which goes along with a video I’ve made about my AWS EC2 Deep Learning setup. The setup goes through the process of installing git, tmux, htop, and security certificates on an EC2 deep learning image. The... Continue →