I have a modal reaction component with a button that opens the modal. The modal also has a close button. Here is the code and what the modal looks like:
class Modal extends React.Component {
static defaultProps = {
title: "Modal Title",
float: false,
color: "pink",
children: <div>Add children here!</div>
}
constructor(props) {
super(props)
this.state = {
show: false
}
}
openModal() {
this.setState(
{ show: true }
)
}
closeModal() {
this.setState(
{ show: false }
);
}
render() {
return (
<div>
<button className={"modal-button" + " " + this.props.color} onClick={() => this.openModal()}>{this.props.title}</button>
{this.state.show && <div className={"modal fade-in" + " " + (this.props.float ? "modal-float" : null)}>
<div className="modal-head">
<span>{this.props.title}</span>
<button id='button' onClick={() => this.closeModal()}>x</button>
</div>
<div className="modal-body">
{this.props.children}
</div>
</div>}
</div>
)
}
}
I would like close the modal clicking outside. In another question I saw a code like this
handleClick = event => {
event.preventDefault();
this.setState({ showModal: true }, () => {
document.addEventListener("click", this.closeMenu);
});
};
closeMenu = () => {
this.setState({ menuOpen: false }, () => {
document.removeEventListener('click', this.closeMenu);
});
}
But it also close the modal when I click inside the modal.