Home » Reactjs » ReactJS call parent method

ReactJS call parent method

Posted by: admin November 30, 2017 Leave a comment

Questions:

I’m making my first step in ReactJS and trying to understand communication between parent and children.
I’m making form, so I have the component for styling fields. And also I have parent component that includes field and checking it. Example:

var LoginField = React.createClass({
    render: function() {
        return (
            <MyField icon="user_icon" placeholder="Nickname" />
        );
    },
    check: function () {
        console.log ("aakmslkanslkc");
    }
})

var MyField = React.createClass({
    render: function() {
...
    },
    handleChange: function(event) {
//call parent!
    }
})

Is there any way to do it. And is my logic is good in reactjs “world”? Thanks for your time.

Answers:

To do this you pass a callback as a property down to the child from the parent.

For example:

var Parent = React.createClass({

    getInitialState: function() {
        return {
            value: 'foo'
        }
    },

    changeHandler: function(value) {
        this.setState({
            value: value
        });
    },

    render: function() {
        return (
            <div>
                <Child value={this.state.value} onChange={this.changeHandler} />
                <span>{this.state.value}</span>
            </div>
        );
    }
});

var Child = React.createClass({
    propTypes: {
        value:      React.PropTypes.string,
        onChange:   React.PropTypes.func
    },
    getDefaultProps: function() {
        return {
            value: ''
        };
    },
    changeHandler: function(e) {
        if (typeof this.props.onChange === 'function') {
            this.props.onChange(e.target.value);
        }
    },
    render: function() {
        return (
            <input type="text" value={this.props.value} onChange={this.changeHandler} />
        );
    }
});

In the above example, Parent calls Child with a property of value and onChange. The Child in return binds an onChange handler to a standard <input /> element and passes the value up to the Parent‘s callback if it’s defined.

As a result the Parent‘s changeHandler method is called with the first argument being the string value from the <input /> field in the Child. The result is that the Parent‘s state can be updated with that value, causing the parent’s <span /> element to update with the new value as you type it in the Child‘s input field.

Questions:
Answers:

You can use any parent methods. For this you should to send this methods from you parent to you child like any simple value. And you can use many methods from the parent at one time. For example:

var Parent = React.createClass({
    someMethod: function(value) {
        console.log("value from child", value)
    },
    someMethod2: function(value) {
        console.log("second method used", value)
    },
    render: function() {
      return (<Child someMethod={this.someMethod} someMethod2={this.someMethod2} />);
    }
});

And use it into the Child like this (for any actions or into any child methods):

var Child = React.createClass({
    getInitialState: function() {
      return {
        value: 'bar'
      }
    },
    render: function() {
      return (<input type="text" value={this.state.value} onClick={this.props.someMethod} onChange={this.props.someMethod2} />);
    }
});

Questions:
Answers:

You can also do it with custom javascript events, jQuery example:

var YourComponent = React.createClass({

    componentDidMount: function(){

        // Register event (the name is just an example of namespacing)
        $(document).on("ReactComponent:YourComponent:myCustomMethod", this.myCustomMethod);
    },

    myCustomMethod: function(){

        // code
    },

    render: function(){
        return (
            // jsx
        )
    }
});

// Trigger event from everywhere
$(document).trigger("ReactComponent:YourComponent:myCustomMethod");

Remember to limit the use of this solution to the “static” React components as much as possible to avoid having too many registered events that you might forget to unregister.