Send data in React via props to parent component
In this article we will build a component in react, that receives an array of data and a component that will display the iteration data.
This allows you to send data arrays with different types to variable components in order to display them there.
For example you could create a grid component which displays an array of articles, video previews, shop items or the team of a company
Grid Component
The grid component iterates through the items array, which was provided via props. The data of the current iteration is then returned to the parent component in order to be handled there.
interface Props {
items: any[];
component: (data: any) => JSX.Element;
}
export default function ComponentGrid(props: Props) {
return (
<div className="row">
{props.items.map((item: any, index: number) => (
<div
className="col-xl-3 col-lg-4 col-md-6 col-12"
key={`item_grid_item_${item.id}`}
>
{props.component(item)}
</div>
))}
</div>
);
}
Parent Component
In the parent component you can receive the data that was sent from the ComponentGrid
. In the following code snippet you can see, that the component
property receives iterationData, which is then handed over to a component named ElementCard
in order to be processed further.
<ComponentGrid
items={data}
component={(iterationData: ArticleInterface) => (
<ElementCard
title={iterationData.title}
description={iterationData.description}
/>
)}
/>
Happy coding!