0
votes

I have a modal wrapper and within it it has react-modal which is an npm module.

In the render method it open base on the this.props.isOpen

<ReactModal 
    contentLabel="modal-big"
    className="modal-big"
    isOpen={this.props.isOpen} 
    shouldCloseOnOverlayClick={true}
>
    {this.content()}
</ReactModal>

and within this.content I have button that should close the modal. But how to change the state of the parent? I can't call this.props.isOpen = false;

2

2 Answers

0
votes

You would need to define a function in the parent component that would set its state to closed for the modal and then pass not only the prop of open but also the function that will change the modal to be closed.

class ParentComponent extends Component {
  constructor() {
    super();

    this.state = {
      open: true
    }
  }


  _closeModal = () => {
    this.setState({
      open: false
    })
  }

  render() {
    return <ChildComponent closeModal={this._closeModal}

  }
}

in your child component you would just executed this.props.closeModal and it would update the parents state and close the modal

0
votes

Call a parent function that is passed down to the child as a prop and set the state in it

class Parent extends React.Component {
     constructor() {
         super();
         this.state = {
            open: false
         }
     }
     closeModal = () => {
          this.setState({open: false});

     }
     render() {
        return (
          <ModalComp closeModal={this.closeModal} open={this.state.open}/>
        )
     }
}

class ModalComp extends React.Component {
   content = () => {
       return (
          <button type="text" onClick={()=> this.props.closeModal()}> close</button>
       )
   }
   render() {
      // .... Modal content here
   }

}