'how to setstate in handleclick in reactjs
im a beginner concerning react .i do not know why setState in the handleclick function doesn't work properly . this is the code
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = { isDark: false }
}
handleOnClick = () => {
this.setState(prevState => ({ isDark: !prevState.isDark }))
if (this.state.isDark === 'true') {
setTheme('theme-dark')
}
else setTheme('theme-light')
}
render() {
return (
<button onClick={this.handleOnClick}>
</button>
so when i click the button the state of isDark will always be false , that means setState is not working i guess
Solution 1:[1]
You need to write this
this.handleOnClick = this.handleOnClick.bind(this);
at the end of your constructor and in handleOnClick function create local variable to save new value:
handleOnClick = () => {
const isDark = !this.state.isDark;
this.setState({ isDark: isDark });
if (isDark === true) {
setTheme('theme-dark')
} else {
setTheme('theme-light');
}
}
Solution 2:[2]
the code is correct but in the conditional statement there is a huge mistake i was comparing this.state.isDark ==='true'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | M.El Yaakoubi |
