I have this React Class component
where I cannot get the Button text to change from on
to off
import React from 'react';
import ReactDOM from 'react-dom';
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {
on: true
}
}
handleClick = () => {
// todo
this.setState((prevState) => {
on: !prevState.on
})
}
render() {
const {
on
} = this.state;
return ( <
button onClick = {this.handleClick} >
{
on ? "On" : "Off"
} < /button>
);
}
}
ReactDOM.render( <
Toggle / > ,
document.getElementById('root')
);
I thought every time the button is clicked it would it would see the previous state and it would update.
You are just missing some parenthesis. If you want to implicitly return an object, you must put them.
handleClick = () => {
this.setState(prevState => ({
on: !prevState.on
}));
};
Check result here