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

Easily log custom metrics to AWS CloudWatch

Recently, I wanted to track the amount of time that Sidekiq jobs were taking to execute on a production Rails environment. I wanted an easy way to be able to track the arguments for the Sidekiq job, the user that initiated the job, and... Continue →