Hello all.
I am having trouble with getting the toggle part of this challenge to work. I started it last week and have been tweeking the code for days. At present, my code passes all tests except: Clicking the button element should toggle the visibility
property in state between true
and false
.
I am thinking the error is in this part of my code:
toggleVisibility() {
this.setState(state => ({
visibility: !state.visibility
}));
}
Before that I tried:
toggleVisibility() {
this.setState(state => {
if (state.visibility === true) {
return { visibility: false };
} else {
return { visibility: true };
}
});
I’ve tried other things as well.
I think I am doing something wrong in the this.setState (At least that’s what the TypeError at the bottom of the screen seems to imply: [TypeError: Cannot read properties of undefined (reading ‘setState’)]).
Full code below:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
visibility: false
};
// Change code below this line
this.toggleVisiblity = this.toggleVisibility.bind(this);
// Change code above this line
}
// Change code below this line
toggleVisibility() {
this.setState(state => ({
visibility: !state.visibility
}));
}
// 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) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36
Challenge: React - Use State to Toggle an Element
Link to the challenge: