B
B
Black_Fire2020-12-04 16:36:34
React
Black_Fire, 2020-12-04 16:36:34

How to close a popup on click outside of it in a class component?

There are two buttons on the page, by clicking on each of them a popup appears with a translucent darkened background. In the App.js state, there are two variables with a value falsefor each modal, which actually change on click on these buttons through this.setStateto true, for their appearance by conditional rendering. How to make a click handler on an area outside the modal in React so that it closes?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-12-04
@Black_Fire

In parent:

state = {
  modal: false,
}

hideModal = () => {
  this.setState({ modal: false })
}

render() {
  return (
    ...
      {this.state.modal ? <Modal close={this.hideModal} /> : null}
    ...
  );
}

In the window component:
return (
  <div
    className="modal-overlay"
    onClick={e => (e.currentTarget === e.target) && props.close()}
  >
    <div className="modal-content">
      ...
    </div>
  </div>
);

https://jsfiddle.net/5d0t9feh/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question