Tell us what’s happening:
Hi! Functionally, my code works - when I click the button, the state seems to toggle and the text appears/disappears from the screen.
But I keep getting an error on the console: “An anonymous function should be passed to setState”. I’ve reviewed my code a couple of times and did some improvements, but I still don’t understand fundamentally what the console call is trying to tell me. I understand the solutions posted on the Guide, but I’d love to know what’s the issue with mine instead. Thanks!
Your code so far
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
visibility: false
};
// Change code below this line
this.toggleVisibility = this.toggleVisibility.bind(this);
// Change code above this line
}
// Change code below this line
toggleVisibility(){
if(this.state.visibility){
this.setState({
visibility: false
})
} else {
this.setState({
visibility: true
})
}
}
// Change code above this line
render() {
if (this.state.visibility) {
return (
<div>
<button onClick={this.toggleVisibility}>Click Me</button>
<h1>Now you see me!</h1>
</div>
);
} else {
return (
<div>
<button onClick={this.toggleVisibility}>Click Me</button>
</div>
);
}
}
}
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:129.0) Gecko/20100101 Firefox/129.0
Challenge Information:
React - Use State to Toggle an Element