How Do I Identify A Material-ui Slider In React?
I want multiple material-ui sliders in one react component sharing a common event handler. However, to make this work, I would need to identify the originating slider. From the API
Solution 1:
You can format your state like so:
state = {
slider1: 50, //slider1 is the name of the first slider
slider2: 50, //slider2 is the name of the second slider
}
After that, you have 2 ways to set the state when the value of the slider is changed:
(Update: This method doesn't work! However I will leave it here for future reference) By using HTML attribute
id
, then access it by usingevent.target.id
. The wholehandleChange
method would look like this:handleChange = (e, value) => { this.setState({ [e.target.id]: value }); }
By passing then name of the slider straight to the
handleChange
method, and it would be like this:handleChange = name =>(e, value) => { this.setState({ [name]: value }); }
Overall, your component should be:
classSimpleSliderextendsComponent {
state = {
slider1: 50,
slider2: 50
};
handleChange = name =>(e, value) => {
this.setState({
[name]: value // --> Important bit here: This is how you set the value of sliders
});
};
render() {
const { classes } = this.props;
const { slider1, slider2 } = this.state;
return (
<divclassName={classes.root}><Typographyid="label">Slider label</Typography><Sliderclasses={{container:classes.slider }}
value={slider1}aria-labelledby="label"onChange={this.handleChange("slider1")}
/><Sliderclasses={{container:classes.slider }}
value={slider2}aria-labelledby="label"onChange={this.handleChange("slider2")}
/></div>
);
}
}
See it in action: https://codesandbox.io/s/4qz8o01qp4
Edit: After running the code I found that the #1 doesn't work because the id attribute is not being passed down to the event target
Post a Comment for "How Do I Identify A Material-ui Slider In React?"