R
Reactiflux

✅ – Alexs – 10-05 Dec 15

✅ – Alexs – 10-05 Dec 15

CComputerScientist12/15/2022
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
UUUnknown User12/16/2022
5 Messages Not Public
Sign In & Join Server To View

Looking for more? Join the community!

R
Reactiflux

✅ – Alexs – 10-05 Dec 15

Join Server