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.fr
Subscribe to get the latest posts sent to your email.