I have the following Modal (TestModal) in a separate component:
<Modal
title="title"
centered={true}
visible={this.props.isOpen}
okText="Close"
onOk={this.props.onClose}
>
Test
</Modal>
Then within another component I have this:
class ModalContainer extends React.Component {
state = {
isModalOpen: false,
}
render() {
return (
<div onClick={() => this.setState({ isModalOpen: true })}>
<TestModal isOpen={this.state.isModalOpen} onClose={() => this.setState({ isModalOpen: false })} />
</div>
);
}
}
Now when I click the container the isOpen prop changes to true and its passed into the Modal which then shows it. Now when I click the isOk button it should close the modal (isModalOpen = false) However nothing happens. When I console.log the value of isModalOpen when I click the "close" button it keeps showing true. For some reason it does not change to false.
Any idea if its a react issue or antd issue?
React: 16.13.1 antd: 4.1.0
This is happening because of the onClick
handler present in div
on ModalContainer
. When the close button is clicked on Modal
the click event bubbles to the div
click handler as well which sets the state to true
again.
The solution for this is to stop the bubbling of click event. You can try doing this:
<TestModal
isOpen={this.state.isModalOpen}
onClose={e => {
e.stopPropagation();
this.setState({ isModalOpen: false });
}}
/>
Here is the same solution implemented in CodeSandbox. Link: https://codesandbox.io/s/ecstatic-bohr-637jo?file=/src/App.js:402-589