DEV Community

Vishnu Satheesh
Vishnu Satheesh

Posted on

How to Build Reusable List Components in React with Custom Render Functions?

When working in React, it's common to have a list component that accepts data and maps over each item to display it. However, different parts of your application may require different renderings for the same data. The best solution for this is to make your list component more flexible by using a render prop to pass a custom rendering function.

Why Is This Necessary?

Imagine you have a list of users in your application. In some areas, you want to display just the user names, and in others, you need to show more detailed information like email addresses or profile pictures. Creating multiple list components for each use case can lead to duplicated code and make the project harder to maintain.

What's the solution?

A simple and elegant solution is to have your list component accept a renderItem function. This function takes an individual item (in our case, a user) as an argument and returns a React node that can be rendered in any way you want.

import React from 'react';

const List = ({ data, renderItem }) => {
  return (
    <ul>
      {data.map((item) => (
        <li key={item.id}>
          {renderItem(item)}
        </li>
      ))}
    </ul>
  );
};

export default List;

Enter fullscreen mode Exit fullscreen mode

How to use this component?

import List from './List';

const users = [
  { id: 1, name: 'John Doe', email: 'john@example.com' },
  { id: 2, name: 'Jane Smith', email: 'jane@example.com' }
];

const UserList = () => {
  return (
    <List
      data={users}
      renderItem={(user) => <span>{user.name}</span>}
    />
  );
};

// or 

const DetailedUserList = () => {
  return (
    <List
      data={users}
      renderItem={(user) => (
        <div>
          <strong>{user.name}</strong>
          <p>{user.email}</p>
        </div>
      )}
    />
  );
};


Enter fullscreen mode Exit fullscreen mode

Why this is a Great Pattern?

This pattern allows for maximum flexibility with minimal code duplication. Instead of creating a different list component for every use case, you have one list component that can handle any rendering requirement.

If you've worked with React Native, this pattern should feel familiar, as it’s used in their list components like FlatList. It’s a proven, reliable solution for rendering lists.

By allowing your list component to accept a renderItem prop, you can easily create reusable components that adapt to different parts of your application. This approach simplifies your codebase, makes it easier to maintain, and enhances the scalability of your application.

Now that you’ve learned this pattern, give it a try in your React projects, and you’ll see how powerful and flexible it is! Happy coding🚀

Top comments (0)