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

137
Visualizações
How to extract values from components that have been rendered in ReactJS?

I'm new to React and I just started a new project to learn it. Currently I'm stuck on how to exact the value from components that have been rendered by another component. I'll give an example code to better explain myself.

Let's say I have built components Fruit and Vegetables, each of them have

this.state = {
   price: 0,
}

and later

this.setState({price:/*randomly generated positive integer*/})

and I try to encapsulate them in a new component called Base. In Base's render() function I have:

render() {
    return (
    <>
        <Fruit></Fruit>
        <Vegetables></Vegetables>
        <button onClick={() => this.add()}>Add Prices!</button>
    </>
    )
}

where as the add() function aims to add the prices of the previously rendered Fruit and Vegetables prices. I've tried to assign them an id and use DOM to grab their values but I could not reach their this.state. Is there a way to achieve this, or alternatively, what is the common practice to do this in React? Thank you in advance for any guidance!

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

0

One common practice is to define the prices in your main component and then pass those prices as props to its children.

Otherwise you could use a state managing library such as Redux to access states from anywhere in your app (this would be way too much for such a simple case)

about 4 years ago · Juan Pablo Isaza Relatório

0

Well, you shouldn't be able to modify react's components state outside of the component by definition. (From parent I think there's no way afaik. But if you want to update from child you could pass down a function via props, from parent to child which updates parent's state).

Simple way to overcome this could be to have prices be defined in Base component's state, then add function in Base component would update Base state. And you could pass prices down to Fruit and Vegetable via props.

Something along these lines:

function Base() {
    const [prices, setPrices] = useState({
        fruit: 20,
        vegetable: 10,
    });

    const add = () => {
        setPrices({
            fruit: prices.fruit + 10,
            vegetable: prices.vegetable + 15
        });
    }

    return (<>
        <Fruit price={prices.fruit}></Fruit>
        <Vegetables price={prices.vegetable}></Vegetables>
        <button onClick={() => this.add()}>Add Prices!</button>
    </>);
}

function Fruit({price})
{
//----
}

function Vegetable({price})
{
//.....
}

However, in complex application passing down props through N number of children can get tedious. In future when your application grows you might want to look at React Contexts. https://reactjs.org/docs/context.html

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