I am trying to change the color of a material-ui Button when it's clicked. I have multiple buttons. When I click on a Button, The color changes for all of them at the same time. How can I only change the one that is clicked. I have the following code, but it's not doing the work, it's supposed to do.
constructor(props){
super(props);
this.state={
videos : data,
filtered: data,
color : "primary"
};
}
handleClick = (event) => {
const value = event.currentTarget.value;
console.log(event);
this.setState({
filtered: this.state.videos.filter(item => {
return item.category === value
}),
color: "secondary"
});
}
<Button value="java" onClick={this.handleClick} variant="contained"
color={this.state.color} >java</Button>
<Button value="React" onClick={this.handleClick}
variant="contained" color={this.state.color}>React</Button>
<Button value="C#" onClick={this.handleClick}
variant="contained" color={this.state.color}>C#</Button>
It looks like this state change is not in the object being passed to setState()
, it should be:
this.setState({
filtered: this.state.videos.filter(item => {
return item.category === value
}),
Color: "secondary"
});
handleClick = (event) => {
const value = event.currentTarget.value;
this.setState({ filtered: this.state.videos.filter(item => {
return item.category === value
}), {Color: "secondary"}
})
}
you just inserted your color inside filter's callback function, just change that it will work
Please check this example:
import React, {useState} from 'react';
import {makeStyles} from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
export default function ContainedButtons() {
const [color, setColor] = useState('primary');
return (
<div>
<Button variant="contained" color={color} onClick={() => {setColor('secondary')}}>
Click Me
</Button>
</div>
);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.