Reputation: 209
I am using material-ui's Button and ButtonGroup. I want to change the color of each button depending on the button pressed (to see the active filter) This is my code:
<ButtonGroup variant="contained" aria-label="contained primary button group" >
<Button value={false} variant="contained" onClick={this.sortOnChange} color={this.state.relevanceColor}>Most Recent</Button>
<Button value={true} variant="contained" onClick={this.sortOnChange} color={this.state.recentColor}>Most Relevant</Button>
</ButtonGroup>
This is the sortOnChange function:
sortOnChange = (event) => {
const value = event.currentTarget.value;
console.log(value);
let recent;
let relevance;
if(value){
recent= "secondary";
relevance="primary";
}else {
recent="primary";
relevance="secondary";
}
this.setState({relevanceColor: relevance, recentColor: recent}, function () {
this.updateResults();
});
}
The updateResults function does nothing for now.
The state is:
relevanceColor: "primary",
recentColor: "secondary",
For some reason the color is not changed at all.
How can I make it so that when you click on one option, them both change color so the clicked button gets the "primary" color and the 'unclicked' button gets the "secondary" color.
Upvotes: 0
Views: 448
Reputation: 6582
sortOnChange = (value) => {
let recent;
let relevance;
if (value) {
recent = "secondary";
relevance = "primary";
} else {
recent = "primary";
relevance = "secondary";
}
this.setState({ relevanceColor: relevance, recentColor: recent }, function() {
this.updateResults();
});
};
<ButtonGroup variant="contained" aria-label="contained primary button group">
<Button
variant="contained"
onClick={() => this.sortOnChange(false)}
color={this.state.relevanceColor}
>
Most Recent
</Button>
<Button
variant="contained"
onClick={() => this.sortOnChange(true)}
color={this.state.recentColor}
>
Most Relevant
</Button>
</ButtonGroup>;
Upvotes: 1