Hello everyone. I just finished this challenge but I have a question: If I would like to create a variable to count how many wins I have, how could I do that? Any suggestions are welcome.
The way we change props
in React is by passing functions which modify state
. Ideally, you’d use a state management library like Redux, but here’s how you’d do it in just React.
class MyStatefulComponent extends React.Component {
state = {
score: 0,
}
constructor(props) {
super(props);
this.incrementScore = this.incrementScore.bind(this);
this.decrementScore = this.decrementScore.bind(this);
}
incrementScore() {
const score = this.state.score + 1;
this.setState({ score });
}
decrementScore() {
const score = this.state.score <== 0 ? 0 : this.state.score - 1 ;
this.setState({ score });
}
render() {
return (
<ScoreCounter
score={this.state.score}
incrementScore={this.incrementScore}
decrementScore={this.decrementScore}
/>
);
}
const ScoreCounter = ({ score, incrementScore, decrementScore }) => (
<React.Fragment>
<button type="button" onClick={decrementScore}> - </button>
{score}
<button type="button" onClick={incrementScore}> + </button>
</React.Fragment>
);
<ScoreCounter />
takes only props
and it modifies the state
of its parent component by calling functions that are bound to that parent’s lexical scope. This just means that using this
in your function refers to the component holding the state. If you don’t use bind
, then this
will refer to whichever function is calling the function. It’s a bit confusion, but you get the hang of it after you forget to use bind
a few times
Thank you for your reply. But I meant how to count my score in this challenge if the expression is true. For example if it is true it says you won. If it false it says you lose. I want it to increment every time the expression is true. How can I do that?