In React, render props are a great way to reuse component logic while customizing how things look.
Letβs say we have two arrays β one for products and one for companies:
const products = [...]; // list of product objects
const companies = [...]; // list of company objects
We want to render both in different ways, but reuse the same logic for listing and toggling visibility.
π§ What Is a Render Prop?
A render prop is just a prop that takes a function. This function controls how each item is rendered.
<Component render={(item) => <div>{item.name}</div>} />
π§ Reusable List
Component
Hereβs a simple List
component using a render prop:
function List({ title, items, render }) {
const [isCollapsed, setIsCollapsed] = useState(false);
const displayItems = isCollapsed ? items.slice(0, 3) : items;
return (
<div>
<h2>{title}</h2>
<ul>{displayItems.map(render)}</ul>
<button onClick={() => setIsCollapsed(!isCollapsed)}>
{isCollapsed ? "Show All" : "Show Less"}
</button>
</div>
);
}
β Rendering Products
<List
title="Products"
items={products}
render={(product) => (
<li key={product.productName}>
{product.productName} - ${product.price}
</li>
)}
/>
β Rendering Companies
<List
title="Companies"
items={companies}
render={(company) => (
<li key={company.companyName}>
{company.companyName} β {company.phrase}
</li>
)}
/>
π― Why Use Render Props?
- Write once, use anywhere
- Clean separation of logic and UI
- Highly reusable components
Thatβs it! One component. Two uses. Clean, simple, and powerful.
π¬ Found this helpful? Drop a β€οΈ or leave a comment!
Top comments (0)