Home > Software engineering >  How to extract values from components that have been rendered in ReactJS?
How to extract values from components that have been rendered in ReactJS?

Time:12-27

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!

CodePudding user response:

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)

CodePudding user response:

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 ammount 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

  • Related