Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

186
Visualizações
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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda