DEV Community

Cover image for Building Reusable List Components in React
Vishal Yadav
Vishal Yadav

Posted on

Building Reusable List Components in React

Introduction

In React development, it's common to encounter scenarios where you need to display lists of similar components with varying styles or content. For instance, you might have a list of authors, each with different information like name, age, country, and books authored. To efficiently handle such cases, we can leverage React's component composition and props passing. In this blog post, we will explore how to build reusable list components in React to achieve this.

Defining the Data

Let's consider a scenario where we have an array of authors, each represented by an object containing their details like name, age, country, and books they've written. We want to create two distinct styles for displaying these authors: a large card displaying all details including their books, and a smaller card with just the name and age.

Firstly, we define our array of authors:

export const authors = [
  {
    name: "Sarah Waters",
    age: 55,
    country: "United Kingdom",
    books: ["Fingersmith", "The Night Watch"],
  },
  {
    name: "Haruki Murakami",
    age: 71,
    country: "Japan",
    books: ["Norwegian Wood", "Kafka on the Shore"],
  },
  {
    name: "Chimamanda Ngozi Adichie",
    age: 43,
    country: "Nigeria",
    books: ["Half of a Yellow Sun", "Americanah"],
  },
];

Creating List Item Components

Next, we create our two different styles of author list items: LargeAuthorListItem and SmallAuthorListItem. The former displays all details including books, while the latter only shows name and age.

Large Author List Item

export const LargeAuthorListItem = ({ author }) => {
  const { name, age, country, books } = author;
  return (
    <>
      <h2>{name}</h2>
      <p>Age: {age}</p>
      <p>Country: {country}</p>
      <p>
        Books:{" "}
        {books.map((book, index) => (
          <span key={index}>{book}</span>
        ))}
      </p>
    </>
  );
};

Small Author List Item

export const SmallAuthorListItem = ({ author }) => {
  const { name, age } = author;
  return (
    <>
      <h2>{name}</h2>
      <p>Age: {age}</p>
    </>
  );
};

Creating a Reusable List Component

Now, to make these components reusable and versatile, we create a RegularList component. This component takes in an array of items, a prop specifying the source of data (in our case, "author"), and the type of item component to render.

export const RegularList = ({ items, sourceName, ItemComponent }) => {
  return (
    <>
      {items.map((item, index) => (
        <ItemComponent key={index} {...{ [sourceName]: item }} />
      ))}
    </>
  );
};

Using the Reusable List Component

With RegularList, we can easily render lists of authors in different styles by passing in the appropriate item component and data source name. For example:

import { authors, RegularList, LargeAuthorListItem, SmallAuthorListItem } from './components';

const App = () => {
  return (
    <div>
      <h1>Authors</h1>
      <h2>Large Cards</h2>
      <RegularList items={authors} sourceName="author" ItemComponent={LargeAuthorListItem} />
      <h2>Small Cards</h2>
      <RegularList items={authors} sourceName="author" ItemComponent={SmallAuthorListItem} />
    </div>
  );
};

export default App;

Benefits of Reusable Components

By utilizing these components, we can easily create and maintain lists of objects with different styles across our application. This approach promotes code reusability and maintainability, making our React application more efficient and scalable.

Code Reusability

Creating reusable components reduces code duplication and ensures consistency across the application. Changes made to a single component will automatically reflect wherever it is used.

Maintainability

With a clear separation of concerns, components are easier to manage and update. This modular approach makes the codebase cleaner and more organized.

Efficiency

Reusable components can improve performance by reducing the need for redundant code execution. This makes the application more efficient and responsive.

Conclusion

Building reusable list components in React is a powerful technique that can simplify your development process and enhance the maintainability of your codebase. By leveraging component composition and props passing, you can create versatile components that adapt to different styles and content requirements. Give this approach a try in your next React project and experience the benefits of reusable components!

If you found this guide helpful, feel free to share it with others and save it for future reference. Stay tuned for more insightful articles on React and web development!

Top comments (8)

 
sanskari_patrick07 profile image
Prateik Lohani β€’ β€’ Edited

Cool post bro!
Just one quick doubt though, what does this line do exactly?

<ItemComponent key={index} {...{ [sourceName]: item }} />

I'm confused about that object destructuring part. The syntax seems a bit confusing to me. I'd be glad if you can explain.

 
vyan profile image
Vishal Yadav β€’

The line dynamically assigns the item object to a prop named by sourceName, such as author.

 
lewiscowles1986 profile image
Lewis Cowles β€’

They are using destructuring to add the prop name from a function argument; using position for the key (which I think might be a mistake). And then taking a single item from the list, to supply object-level data.

See

<RegularList items={authors} sourceName="author" ItemComponent={LargeAuthorListItem} />

It's an interesting design choice, but as you are pointing out, the code complexity is high; and I'm not sure it's readable, or intention revealing. Check with your team before blindly copying.

To the original author. Wouldn't this make it harder / more convoluted to bind actions to components?

 
panchalmukundak profile image
Mukunda Panchal β€’

Hi, please go through this for answer of your question.

Answer of your question

 
heyeasley profile image
heyeasley πŸ“πŸ₯­ β€’

Wow. Useful. How did you make moving profile's GIF ? It's impressive.

 
shaogat_alam_1e055e90254d profile image
Shaogat Alam β€’

Interesting topic! The examples are easy to follow and very practical. Well done! You might also find this free npm package useful for your project: select-paginated. Check it out!

 
vyan profile image
Vishal Yadav β€’

Thanks!

 
joshua_mcmillan_3e37d7136 profile image
Joshua McMillan β€’

Nice article! The whole concept of β€œreusability” is a big one, as it expend past not just the components system design, but how they should be in sync with a design system with easy to manage/discover available components, to avoid rebuilding existing ones.

Vishal, I’m curious if you have a spare moment, to give your thoughts on this?
dev.to/joshua_mcmillan_3e37d7136/b...

My team are trying to solve this broader issue of reusability :)