Well, I will try to do it quickly, because SHOULD be an easy solution ...
I read a bunch of similar questions, and the answer seems quite obvious. Nothing I'd ever need to look for in the first place! But ... I have a mistake that I cannot understand how to fix or why this is happening.
Properly:
class NightlifeTypes extends Component { constructor(props) { super(props); this.state = { barClubLounge: false, seeTheTown: true, eventsEntertainment: true, familyFriendlyOnly: false } this.handleOnChange = this.handleOnChange.bind(this); } handleOnChange = (event) => { if(event.target.className == "barClubLounge") { this.setState({barClubLounge: event.target.checked}); console.log(event.target.checked) console.log(this.state.barClubLounge) } } render() { return ( <input className="barClubLounge" type='checkbox' onChange={this.handleOnChange} checked={this.state.barClubLounge}/> ) }
More code surrounds this, but this is my problem. Should work, huh?
I also tried this:
handleOnChange = (event) => { if(event.target.className == "barClubLounge") { this.setState({barClubLounge: !this.state.barClubLounge}); console.log(event.target.checked) console.log(this.state.barClubLounge) }
So, I have those two console.log()
, both should be the same. I literally set the state just like event.target.checked
in the line above it!
But he always returns the opposite of what he needs.
The same thing happens when I use !this.state.barClubLounge
; If it starts with false, my first click remains false, even if the checkbox is checked or not based on state !!
This is a crazy paradox, and I have no idea what is going on, please help!
source share