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() {
  return(<div>{dynamicComponent}</div>)
}

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

 
4
Kudos
 
4
Kudos

Now read this

3 apps that every college student should use

These apps will super-charge your life. They’ll make you more productive than you’ve ever been. They’ll pretty much write that 900 word essay you’ve been procrastinating on. Here’s a list of 3 incredibly sexy apps that are available on... Continue →