Reputation: 758
In my main component, Game, which holds two state properties which are arrays of cards, easyCards and hardCards, I render two Button components. The Button components are presentational, they just render a prop passed in. I am trying figure out based on which button I click, How can I pass one of the two card arrays to the Card component as props to render them?
handleEasyCards() {
}
handleHardCards() {
}
render() {
return (
<div>
<Timer />
<div>
<Button difficulty={this.state.easyButton} onClick={this.handleEasyCards}/>
<Button difficulty={this.state.hardButton} onClick={this.handleHardCards}/>
</div>
<Card cardTypes={ // I want to pass a specific state property here} />
</div>
);
}
}
Should this be an onClick method or something that can be handled in the render method? Codesandbox
Upvotes: 2
Views: 401
Reputation: 5198
You're on the right track. Easiest way I can see from here is this:
handleEasyCards() {
this.setState({currentCards: this.state.easyCards});
}
handleHardCards() {
this.setState({currentCards: this.state.hardCards});
}
And then in the render:
<Card cardTypes={this.state.currentCards} />
And then just be sure to handle the render in the Card
component when currentCards
is undefined
, or specify a default.
One caveat that might be applicable, React will optimize out clicking on the same card type, since that will assign to currentCards the same array reference, and it will (rightly) think the state hasn't updated. If you want to show some kind of feedback (reset the cards, animation, whatever) you will need to do something like this:
this.setState({currentCards: [...this.state.easyCards]});
To create a new array to force react to update.
Upvotes: 1