How to Dynamically Render Components in React

Andrew Lee - May 2 '20 - - Dev Community

Sometimes we need to dynamically render React components. For example let's say we are building a drag and drop website builder.

Customer A wants their website to consist of Navbar2, Content1, and Footer3.

<div>
  <Navbar2 />
  <Content1 />
  <Footer3 />
</div>
Enter fullscreen mode Exit fullscreen mode

Customer B on the other hand wants a slightly different website.

<div>
  <Navbar1 />
  <Content3 />
  <Footer1 />
</div>
Enter fullscreen mode Exit fullscreen mode

If we have a lot of components, we are going to end up creating a component for every single possible combination...or we can use dynamic rendering.

First, we need a mapping of our components.

// i.e. const Navbar1 = () => <div>Navbar1</div>

const componentMapping = {
  Navbar1,
  Navbar2,
  Navbar3,
  Content1,
  Content2,
  Content3,
  Footer1,
  Footer2,
  Footer3
};
Enter fullscreen mode Exit fullscreen mode

Then we can render the website for Customer A

const customerA = ['Navbar2', 'Content1', 'Footer3'];
Enter fullscreen mode Exit fullscreen mode

and for Customer B

const customerB = ['Navbar1', 'Content3', 'Footer1'];
Enter fullscreen mode Exit fullscreen mode

with the same dynamic component.

// <Website config={customerA} />
// <Website config={customerB} />

const Website = (props) => {
  return (
    <div>
      {config.map((componentName) => {
        const Component = componentMapping[componentName];
        return <Component />;
      })}
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player