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>
Customer B on the other hand wants a slightly different website.
<div>
<Navbar1 />
<Content3 />
<Footer1 />
</div>
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
};
Then we can render the website for Customer A
const customerA = ['Navbar2', 'Content1', 'Footer3'];
and for Customer B
const customerB = ['Navbar1', 'Content3', 'Footer1'];
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>
);
};