Home > Enterprise >  Passing a Count from a Child Component to the Parent
Passing a Count from a Child Component to the Parent

Time:05-20

hi Everyone I'm just learning to react and ran into a problem I'm making a bunch of counter components that look like this :this is the counters that I'm making

now the problem is that I have defined the state in each of these counters which is 3 of them and id like to pass the value (number) into the parent so I can add it up and display the total count.

here is my child counter component:

import React, { useState } from "react";
const Counter = () => {
    const [count, setcount] = useState(0)
    const handleIncrement=()=>{

        setcount(count 1);
    }
    const handleDecrement=()=>{

        setcount(count -1);
    }

  return (
    <div>
      <button onClick={()=>{handleIncrement()}}> </button>
      <span>{count}</span>
      <button onClick={()=>{handleDecrement()}}>-</button>
    </div>
  );
};

export default Counter;

and here is the parnent which iwant to pass my values to so i can add them up and show the total :

import React from 'react'
import Counter from './Counter'
const Counters = () => {
  return (
    <>
    <h3>totalcount:</h3>
    <Counter/>
    <Counter/> 
    <Counter/> 

    </>
  )
  
}

export default Counters

now what I tried was to make multiple states but I can't get a good way to make this I know there's an easy answer for this and I'm making it all title too complicated if you guys have other optimization for my code please share

CodePudding user response:

In React state goes top to bottom. A nested component can update the state of a parent if a function defined in the parent has been passed to it as props. Which means, what you wanna do is not possible as your code is set up. A way to achieve what you are looking for is :

import React, { useState } from "react";
const Counter = ({count, setCount}) => {
  
    const handleIncrement=()=>{
        setCount(count 1);
    }
    const handleDecrement=()=>{
        setCount(count -1);
    }

  return (
    <div>
      <button onClick={()=>{handleIncrement()}}> </button>
      <span>{count}</span>
      <button onClick={()=>{handleDecrement()}}>-</button>
    </div>
  );
};

export default Counter;
import React,{useState} from 'react'
import Counter from './Counter'
const Counters = () => {
  const [countOne, setCountOne] = useState(0)
  const [countTwo, setCountTwo] = useState(0)
  const [countThree, setCountThree] = useState(0)
  return (
    <>
    <h3>totalcount: {countOne   countTwo countThree} </h3>
    <Counter count = {countOne} setCount = {setCountOne} />
    <Counter count = {countTwo} setCount = {setCount} />
    <Counter count = {countThree} setCount = {setCountThree} />

    </>
  )
  
}

export default Counters
  • Related