Null Salad
Null Salad

Reputation: 1030

Material UI: how to get slider values with a button's onClick event?

I have a form consisting of several sliders with a submit button at the end.

In a non-react environment, I would typically have a function that's called for the button's onClick property, where it would iterate through all the sliders and go document.getElementById('mySliderIdX').value.

But with Material UI in React, I cannot access slider values this way. If I try and do this, I get a span element with no value property.

How do I get the value of all my sliders using a button?

My code is here:

let getSliderValues = function (arrOfIDs) {
  let ratings = {}
  arrOfIDs.forEach(name_id => {    
    let slider = document.getElementsByName(name_id);
    ratings[name_id] = slider.value // this is undefined
  });
  console.log("slider values: ",ratings)
}

class MySliders extends Component(){
this.sliders = ["a","b","c"]

render(){
  return(
    <div>
      <Slider id={this.sliders[0]} />
      <Slider id={this.sliders[1]} />
      <Slider id={this.sliders[2]} />
      <button onClick={e=>this.getValues(this.sliders)}>submit</button>
    </div>
  )
}
}

Upvotes: 0

Views: 1413

Answers (1)

Arthur Rubens
Arthur Rubens

Reputation: 4706

You must use value property of the component. Something like this:

import React, { useState } from 'react';
import Button from '@material-ui/core/Button';
import Slider from '@material-ui/core/Slider';


export default function DiscreteSlider() {
  const [ratings, setRatings] = useState([0, 0, 0]);
  let getSliderValues = function () {
    console.log("slider values: ", ratings)
  }
  const getSliders = () => {
      const sliders = [];
      ratings.forEach((rating, index) => {
        sliders.push(<Slider
          key={index}
          value={ratings[index]}
          onChange={(event, newValue) => {
            ratings[index] = newValue;
            const newRatings = [...ratings];
            setRatings(newRatings);
          }}
        />)
      });
      return sliders;
  }

  return (
    <div>
      {getSliders()}
      <Button onClick={e=>getSliderValues()}>submit</Button>
    </div>
  );
}

Upvotes: 2

Related Questions