Ad

React Container Scope Is Not Inherited By Component

I've seperated container and component and now facing the issues with rerendering component.

render() {
    return <DomainEdit schema={this.props.schema} domain={this.domain} formData={this.props.formData} updateSubType={this.updateSubType} types={this.props.types}/>;
}

I am sending updateSubType method which is a callback method whenever anything in the form is changed.

After its changed I am sending back what is changed and I have to update this.props.schema in order to re-render the component with the new schema.

The problem I am facing is that the callback methods this is the scope of the component and not container itself, in other words component only has the arguments I've sent in the render method, which is a problem because I can't access the container props and re-render the component.

How could I re-render the component in the callback method which is defined in the container ?

Ad

Answer

It looks like a context binding issue.

If you want updateSubType to be called inside DomainEdit and still have this inside this callback pointing to the container reference, you have to bind updateSubType to the container instance.

Two ways are available to do this: In the constructor of the container, redefine this.updateSubType = this.updateSubType.bind(this);

Or if you're using ES6, define updateSubType this way:

updateSubType = () => {
    ...method definition
}

The arrow function notation (() => {}) auto binds the function to the surrounding instance.

Ad
source: stackoverflow.com
Ad