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

Your javascript webapps don’t actually need javascript.

Daniel Ricciardo doesn’t have anything to do with this article. Tl;dr: I made my personal website almost twice as fast by porting it from Nuxt to Astro. I made it so that zero JavaScript is sent to the browser[1] . Some background # I... Continue →