1

Given the code below, I would like the transform() method to run anytime this.props.code changes.

class Editor extends Component {
    render() {
        return (
            <div id="pseudo-editor" />
        );
    }

    transform() {
        var editor = ace.edit("pseudo-editor");
        editor.setValue(this.props.code,1);
    }
}

I am using react-redux and the state to props binding works as intended.

But Im not quite sure how to approach method binding. I guess its not an alternative to fit my JS code editors API calls inside the render method. Problably a simple solution to this one but could not find an example of which pattern to use here. Thankful for any help.

1
  • 1
    Use componentWillReceiveProps lifecycle method Commented Jan 9, 2018 at 16:33

1 Answer 1

1

Use componentWillReceiveProps lifecycle method, it will get called whenever any change happens to props values, check the previous and nextProps values if they are not same call the transform method.

Like this:

componentWillReceiveProps(nextProps){
    if(this.props.code != nextProps.code)
        this.transform();
}

As per DOC:

componentWillReceiveProps() is invoked before a mounted component receives new props. If you need to update the state in response to prop changes (for example, to reset it), you may compare this.props and nextProps and perform state transitions using this.setState() in this method.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.