1
votes

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?

2

2 Answers

4
votes

Here's how you can do it. And here's the working example JSBin: https://jsbin.com/yixano/2/edit?html,js,output

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

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

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

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.

2
votes

You can create a method on the parent component that updates the state of showModal and pass it down as a callback to the child component on props. Define a function on the child component that executes the function passed down on props. Set an onClick listener on the 'x' that closes the model, so the child function will be called, executing the function that lives on the parent. This should update state on the parent and cause both to re-render.

class MyParent extends Component {
  toggleShowModal(){
    this.setState({showModal: !this.state.showModal})
  }

  render(){
  return (
    <Modal toggleShowModalCallback={this.toggleShowModal.bind(this)} />
   )
  }

}

class Modal extends Component {

  updateParent(){
    this.props.toggleShowModalCallback()
  }

  render(){
    return(
    <CloseModalButton onClick={this.updateParent.bind(this)} />
    )
  }
}