flowoverstack
flowoverstack

Reputation: 112

React, passing state from a Child component to the Parent

I'm just learning 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

The problem is that I have defined the state in each of these counters which is 3 of them and I'd 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 parent which I want 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

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 too complicated. If you guys have other optimization for my code please share.

Upvotes: 3

Views: 6207

Answers (1)

Youssouf Oumar
Youssouf Oumar

Reputation: 45845

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. This means, what you wanna do is not possible as your code is set up. A way to achieve what you are looking for is:

  1. Pass setCounter down to each Counter instance as props, like so:
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
  1. Get setCounter from the props inside Counter and use it where you want:
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;

Upvotes: 3

Related Questions