import React, { Component } from 'react';
import ReactDOM from 'react-dom'
class Modal extends Component {
state = {
isActive: false,
isMounted: false
}
componentDidMount() {
this.setState({
isMounted: true
})
}
componentDidUpdate(prevProps, prevState) {
if (!prevState.isActive && this.state.isActive) {
document.addEventListener('click', this.hideModal)
}
if (prevState.isActive && !this.state.isActive) {
document.removeEventListener('click', this.hideModal)
}
}
componentWillUnmount() {
document.removeEventListener('click', this.hideModal)
}
hideModal = (e) => {
if (!this.state.isMounted) return false
const node = ReactDOM.findDOMNode(this)
const target = e.target || e.srcElement
const isInside = node.contains(target)
if (this.state.isActive && !isInside) {
this.setState({
isActive: false
})
}
}
showModal = () => {
this.setState({
isActive: true
})
}
render() {
return (
<div>
{this.state.isActive && <div>Modal</div>}
<button onClick={this.showModal}>showModal</button>
</div>
);
}
}
export default Modal;