Zhihar
Zhihar

Reputation: 1428

react: reach the component's parent or transfer data from parent to child

Please tell me how you can in this scheme

render()
{
    return (
<Parent>
    <Child1>
    <Child2>
</Parent>
    );
}

on the side of the components Parent and Child get the data that will be generated in the render () method or in the constructor (data access)

It is clear that one of the ways is to transfer to props, but if without it?

For example, a state is set, in the Parent constructor, this state of the parent is obtained and the same state is set, in the Child constructor, the Parent state is obtained and its state is set. As a result, some parameter is passed across the tree.

But in order to implement this, you need to somehow gain access to the parent of the component.

For example:

more beautiful option (and I do not know how to implement it - this option would be more preferable)

this.state = {
    mydata: 123;
};

class Parent extends Component
{
    constructor()
    {
        super();

        this.state = {
            mydata: this.getOwner().state.mydata; // = 123
        };
    }
}

class Child extends Component
{
    constructor()
    {
        super();

        this.state = {
            mydata: this.getOwner().state.mydata; // = 123
        };
    }
}

less beautiful option (I know how to implement it)

render()
{
    return (
<Parent mydata = "123">
    <Child1 mydata = "123">
    <Child2 mydata = "123">
</Parent>
    );
}

class Parent extends Component
{
    constructor(props)
    {
        super();

        this.state = {
            mydata: props.mydata
        };
    }
}

class Child extends Component
{
    constructor(props)
    {
        super();

        this.state = {
            mydata: props.mydata
        };
    }
}

Upvotes: 0

Views: 142

Answers (1)

sh.alawneh
sh.alawneh

Reputation: 649

you can achieve the wanted result by using something called Context as the following:

 //outside of your class component
    const MyContext = React.CreateContext();
//inside your class component
        state = {mydata: "123"}

        render()
        {
            return (
        <MyContext value={this.state}>
        <Parent>
            <Child1>
            <Child2>
        </Parent>
        </MyContext>
            );
        } 

now inside any of the tree components: Parent Child1 and Child2 you can reach the value of the shared state by saying this.context.mydata

learn more at https://reactjs.org/docs/context.html

Upvotes: 1

Related Questions