Home > Blockchain >  How to set property of a React component in its constructor
How to set property of a React component in its constructor

Time:03-12

In my React code, I want to create a component like

export class MyParentComponent extends React.Component {
....
    public render() {
        return (
                    <MyChildComponent page={this}/>
       )
    }
}

And in the MyChildComponent 's constructor, how can I store a reference to 'MyParentComponent' in the constructor?

class MyChildComponent extends React.Component {
    parent: MyParentComponent;

    constructor(props: Props) {
        super(props);
        this.parent = ....??
    }
}

CodePudding user response:

Have you tried just doing:

class MyChildComponent extends React.Component {
    parent: MyParentComponent;

    constructor(props: Props) {
        super(props);
        this.parent = props.page; // <--- THIS
    }
}
  • Related