Reputation: 1141
I've got a very simple component where I'd like to render a 'cookiePopup' based on whether the state 'cookieShow' is true or false. I'd like to switch the state to false by clicking the 'cookie close container', thereby removing the component. This is done through a ternary operator which if 'cookieShow' is true will render the component, if it's false it will return 'null'.
However, whenever the page loads, the cookiePopup doesn't show. I think this is due to my ternary operator, as it feels like this is something straightforward but can't figure it out.
Here's my code:
class CookiePopup extends Component {
constructor(props) {
super(props)
this.state = {
cookieShow: true
}
this.handleClick = this.handleClick.bind(this)
this.showCookiePopup = this.showCookiePopup.bind(this)
this.removeCookiePopup = this.removeCookiePopup.bind(this)
}
handleClick() {
this.setState(state => ({
cookieShow: false
}));
}
showCookiePopup() {
return (
<div className="cookie-popup-container">
<div onClick={this.handleClick} className="cookie-close-container">
<span className="cookie-close-span-1"></span>
<span className="cookie-close-span-2"></span>
</div>
<div className="cookie-text-container">
<p className="cookie-text">By using our website, you agree to our <a class="cookie-link" href="/cookies" target="_self">cookies</a> policy.</p>
</div>
</div>
)
}
removeCookiePopup() {
return (
null
)
}
render() {
return (
<div>
{ this.state.cookieShow ? this.showCookiePopup : this.removeCookiePopup }
</div>
)
}
}
Not sure what I'm doing wrong, but any advice would be appreciated! Thank you.
Upvotes: 0
Views: 438
Reputation: 237
Concerning the render problem, I would say it's because you do not execute the functions in your ternary, try to add the parenthesis like so :
{ this.state.cookieShow ? this.showCookiePopup() : this.removeCookiePopup() }
The following ain't causing your problems, but you could better code wise :
You don't need to bind your methods in the constructor if you use arrow functions, like so :
removeCookiePopup = () => { // TODO }
I'm not sure about the way you wrote your setState, if someone else can confirm it's a valid way to write it ? Anyway, usually we write it this way :
this.setState({ cookieShow: false });
Or even better, you can use the previous value of the state, as React states it's the way to go (https://reactjs.org/docs/state-and-lifecycle.html), like this :
this.setState((previousState) => ({ cookieShow: !previousState.cookieShow}) );
which will toggle your modal between true and false, meaning you only need one method to open and close it.
Upvotes: 1
Reputation: 2104
Try this
{ this.state.cookieShow ? this.showCookiePopup() : this.removeCookiePopup() }
Upvotes: 1