A Simple Reusable List Component

A Simple Reusable List Component

In this example, SimpleList accepts an items prop, which is an array. We use the .map() function to iterate through the array and render each item inside an unordered list (<ul>). Each item is wrapped in a <li> element. The key prop ensures that React can efficiently update the DOM when the list changes.

import React from ‘react’;

const SimpleList = ({ items }) => {
return (
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
);
};

export default SimpleList;

In this example, the renderItem prop allows us to customize how each user is displayed. Now we can reuse the same list component for any data structure, rendering it according to the specific use case.

const App = () => {
const users = [
{ id: 1, name: ‘John Doe’, age: 30 },
{ id: 2, name: ‘Jane Smith’, age: 25 },
];

return (
<div>
<h1>User List</h1>
<ReusableList
items={users}
renderItem={(user) => (
<div>
<h2>{user.name}</h2>
<p>Age: {user.age}</p>
</div>
)}
/>
</div>
);
};


Discover more from Kvnbbg

Subscribe to get the latest posts sent to your email.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *

Blue Captcha Image
Refresh

*

To respond on your own website, enter the URL of your response which should contain a link to this post's permalink URL. Your response will then appear (possibly after moderation) on this page. Want to update or remove your response? Update or delete your post and re-enter your post's URL again. (Find out more about Webmentions.)