Nicholas Haley Nicholas Haley - 1 year ago 79
React JSX Question

How can I change the state of a parent component from a child component?

I have a parent component which has a boolean state property "showModal". When showModal is true, I render the child component, "Modal". This Modal has a close button which should toggle the "showModal" property back to false. "showModal" is passed to the child Modal component as props, but because props are immutable in React I haven't figured out the correct pattern for changing it.

Is there some sort of two-way data binding I can tap into? What is the best way of dealing with this?

Answer Source

Here's how you can do it. And here's the working example JSBin:,js,output

var ModalParent = React.createClass({
  getInitialState: function() {
    return {showModal: false};

  toggleShowModal: function() {
    this.setState({showModal: !this.state.showModal});

  render: function() {
    return (
        <button type="button" onClick={this.toggleShowModal.bind(this)}>Toggle Show Modal</button>
        {this.state.showModal ? 
            <Modal onModalClose={this.toggleShowModal.bind(this)}/> : 
        <h4>State is: </h4>
        <pre>{JSON.stringify(this.state, null, 2)}</pre>

var Modal = React.createClass({
  render: function(){
    return <div><button type="buton" onClick={this.props.onModalClose}>Close</button></div>

ReactDOM.render(<ModalParent/>, document.getElementById("app"));

The idea here is to pass in a reference to a function on ModalParent to the Modal so that the state in the parent can be altered based on the actions in the child.

As you can see, the child has a prop called "onModalClose" and it needs a function reference which gets invoked on clicking the close button. And in the parent we bind the corresponding toggleShowModal to this onModalClose property.