Reputation: 65
I'm working on a modal in React and have it working successfully elsewhere in my application. However, in the following code snippet, this.state.display
is never being set to false
. I can console log around it, see that the function is firing, but this.state.display
is set to true
after initialization throughout the entire lifecycle.
class AdvancedToDoModal extends Component {
constructor(props) {
super();
this.state = {
display: false,
modalContent: this.fetchModalContent(props)
}
this.fetchModalContent = this.fetchModalContent.bind(this);
this.numberInput = this.numberInput.bind(this);
this.dateInput = this.dateInput.bind(this);
this.showModal = this.showModal.bind(this);
this.hideModal = this.hideModal.bind(this);
}
numberInput() {
return (
<div>Number Input</div>
)
}
dateInput() {
return (
<div>Date Input</div>
)
}
showModal() {
this.setState({ display: true })
}
hideModal() {
console.log('hide')
this.setState({ display: false }, () => {
console.log('display is always true: ', this.state)
});
}
fetchModalContent(props) {
var modalContent;
if (props.inputType === 'number') {
modalContent = this.numberInput();
} else if (props.inputType === 'date') {
modalContent = this.dateInput();
} else {
modalContent = null;
console.log('Unknown inputType');
}
return modalContent;
}
render() {
return (
<div onClick={this.showModal} className={this.state.display} style={{height: '100%', width: '100%'}}>
<Modal display={this.state.display} title={this.props.title} onClose={this.hideModal} >
{this.state.modalContent}
</Modal>
</div>
)
}
}
Any pointers would be appreciated!
Upvotes: 1
Views: 2423
Reputation: 16472
The problem with your code is that you have one onClick handler on a parent element which sets the state when you click close button. Look at your render function
render() {
return (
<div onClick={this.showModal} className={this.state.display} style={{height: '100%', width: '100%'}}>
<Modal display={this.state.display} title={this.props.title} onClose={this.hideModal} >
{this.state.modalContent}
</Modal>
</div>
)
}
Here at the root div you have onClick handler which calls showModal which sets the display
state to true. Now when in modal you click on any close button that calls your hideModal
, but after that, your parent div's onClick
is also called which sets you state again to true. Therefore your display
state always remain true. Remove this onClick
handler and it will be fixed.
Upvotes: 4