StillDead StillDead - 12 days ago 5
Javascript Question

Open a modal from a component

I am working on a component where I need to display and hide a modal.

this is what I have in the render method in React

<div style={{visibility : this.state.displayModal}}>
<p>Pop up: Bet Behind Settings</p>
</div>
<button onClick={this._openModal}>CLICK</button>


and here is the function

_openModal = () => {
if (this.state.displayModal === 'hidden') {
this.setState({
displayModal : 'visible',
})
} else {
this.setState({
displayModal : 'hidden',
})
}
}


the main concern I have, is, how to set the state in a more elegant way, or this should be the way to do it ?

here the full code

constructor (props) {
super(props);
this.state = {
displayModal : 'hidden',
}
}

render () {

return (
<div style={{visibility : this.state.displayModal}}>
<p>Pop up: Bet Behind Settings</p>
</div>
<button onClick={this._openModal}>CLICK</button>
)
}

_openModal = () => {
if (this.state.displayModal === 'hidden') {
this.setState({
displayModal : 'visible',
})
} else {
this.setState({
displayModal : 'hidden',
})
}
}


so, what should be the way to this pop up in a React way.

Answer

I think it's a good way to do it. But it will be more concise if you make displayModel a boolean:

_toggleModal = () => this.setState({displayModal: !this.state.displayModal})
Comments