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.

 
5
Kudos
 
5
Kudos

Now read this

Redis won’t talk to Web Server.

The Problem: # Thinking you’ve correctly configured everything in your shiny new cloud architecture, and having a key piece not work properly can be extremely frustrating. For me, it was trying to get a web server (on EC2) to talk to a... Continue →