⊗jsrtPmCpPS 85 of 112 menu

Passing states to child components in React

Let us have an array with products:

const initProds = [ {id: id(), name: 'product1', cost: 100}, {id: id(), name: 'product2', cost: 200}, {id: id(), name: 'product3', cost: 300}, ];

Let this array be located in the component Products. Let's write these products to the component state:

function Products() { const [prods, setProds] = useState(initProds); }

Now let's loop through the products and display them in some layout:

function Products() { const [prods, setProds] = useState(initProds); const items = prods.map(prod => { return <div key={prod.id}> name: <span>{prod.name}</span>, cost: <span>{prod.cost}</span> </div>; }); return <div> {items} </div>; }

As you can see, the contents of our map cycle are quite complex, especially if the product layout grows in the future. Such complexity makes the code difficult to read, understand, and maintain.

It would be better to move the code responsible for displaying the product to a separate component. Let's call it Product. Here is the code for our component:

function Product({ name, cost }) { return <div> name: <span>{name}</span>, cost: <span>{cost}</span> </div>; }

Now let's use the child components Products inside the map component in the Products cycle:

function Products() { const [prods, setProds] = useState(initProds); const items = prods.map(prod => { return <Product key ={prod.id} name={prod.name} cost={prod.cost} />; }); return <div> {items} </div>; }

As you can see, the cycle code has now been simplified and made more understandable. In addition, a separate component is now responsible for displaying the product, in which we can make and then edit the layout of products.

Technically, we have a parent component that has a state with data, and child components receive this data in the form of props and display it in the way we need.

The state of the Users component contains the following array:

const initUsers = [ {id: id(), name: 'user1', surname: 'surn1', age: 30}, {id: id(), name: 'user2', surname: 'surn2', age: 31}, {id: id(), name: 'user3', surname: 'surn3', age: 32}, ];

Loop through this array and display all users on the screen. Create a separate component User to display the user.

byenru