Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get data from multiple child component in ReactJS

I was having a parent component named Cart.jsx in react and the child component named Card.jsx.

The Parent component looks like this.

Cart.jsx

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import React, { useState, useEffect, useContext } from "react";
import Card from "../../Components/Card";

function Cart() {
   const cart = [**Array of Objects**]
   const [total,setTotal] = useState([]);

      return (
        <div className="cart__Items">
           <Card item={cart[0]} />;
           <Card item={cart[1]} />;
           <Card item={cart[2]} />;
        </div>
      )
}

export default Cart;

And the Card Component looks as follows

Card.jsx

import React, { useState } from "react";

function Card() {
   const [price,setPrice] = useState(0);
    
   // in-between implemented some function to calculate price value.

      return (
        <div>
         // rendering code 
        </div>
      )
}

export default Card;

Now the problem is, how do I get the price data of each child component and store them in the total array of the parent component.

Here the parent has 3 Cardcomponents, I need to get the price data from each component and store them in the Cart component

>Solution :

Here is the code. I hope this might help

 import React, { useState, useEffect, useContext } from "react";
 import Card from "../../Components/Card";

 function Cart() {
  const cart = [**Array of Objects**]
  const [total,setTotal] = useState(0);

  return (
    <div className="cart__Items">
       {cart.map(crt =><Card item={crt} total={total} setTotal={setTotal} />}
    </div>
  )
}

export default Cart;


import React, { useState } from "react";

function Card(props) {
   const [price,setPrice] = useState(0);
   const {setTotal, total} = props
   useEffect(()=>{
      setTotal(total+price)
   },[])
   // in-between implemented some function to calculate price value.

  return (
    <div>
     // rendering code 
    </div>
  )
}

export default Card;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading