How to Dynamically Render Components in React
Andrew Lee
Posted on May 2, 2020
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>
);
};
💖 💪 🙅 🚩
Andrew Lee
Posted on May 2, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
react Handling Dynamic Role Names in Different Environments with useRoleManagement Hook (Part 2)
September 2, 2024