✅ – Alexs – 10-05 Dec 15

I'm currently reading the React docs ( the state States and Lifecycle section) and I just want to have some clarity on a specific part of this code.
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};

// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}

handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}

render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};

// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}

handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}

render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
On the handleClick() function is the setState lifecycle just taking the "this.state" property of your class and switching it to the negated value?
Solution:
Message Not Public
Sign In & Join Server To View
Jump to solution
3 Replies
Solution
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
reactibot
reactibot2y ago
This question has an answer! Thank you for helping 😄 If you have a followup question, you may want to reply to this thread so other members know they're related. https://discord.com/channels/102860784329052160/902647189120118794/1052889093354303518
reactibot
reactibot2y ago
This thread hasn’t had any activity in 12 hours, so it’s now locked. Threads are closed automatically after 12 hours. If you have a followup question, you may want to reply to this thread so other members know they're related. https://discord.com/channels/102860784329052160/902647189120118794/1052889093354303518 Question not getting answered? Maybe it's hard to answer, or maybe you asked at a slow time. Check out these resources for help asking a good question: https://stackoverflow.com/help/how-to-ask http://wp.me/p2oIwo-26