Creating a Reusable List Component with Render Props
Create a List component that accepts a render prop, allowing the parent to dictate how each item in a list is rendered.
class List extends React.Component {
render() {
const { items, renderItem } = this.props;
return (
<ul>
{items.map((item, index) => (
<li key={index}>{renderItem(item)}</li>
))}
</ul>
);
}
}
This is a `List` component which accepts `items`, an array of elements to be listed, and `renderItem`, a render prop function that defines how each item should be rendered.
const App = () => {
const fruits = ['Apple', 'Banana', 'Cherry'];
return (
<List
items={fruits}
renderItem={(item) => <strong>{item}</strong>}
/>
);
};
The `App` component uses the `List` component, passing it an array of fruits and a `renderItem` prop that specifies how each fruit should be rendered—in this case wrapped in `<strong>` tags.