DEV Community

Afaq Shahid Khan
Afaq Shahid Khan

Posted on

πŸ” Reuse React Components with Render Props (Short & Simple)

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
Enter fullscreen mode Exit fullscreen mode

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>} />
Enter fullscreen mode Exit fullscreen mode

πŸ”§ 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>
  );
}
Enter fullscreen mode Exit fullscreen mode

βœ… Rendering Products

<List
  title="Products"
  items={products}
  render={(product) => (
    <li key={product.productName}>
      {product.productName} - ${product.price}
    </li>
  )}
/>
Enter fullscreen mode Exit fullscreen mode

βœ… Rendering Companies

<List
  title="Companies"
  items={companies}
  render={(company) => (
    <li key={company.companyName}>
      {company.companyName} β€” {company.phrase}
    </li>
  )}
/>
Enter fullscreen mode Exit fullscreen mode

🎯 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)