Skip to content
Advertisement

How to store the new updated values with keys from slider Material UI ReactJS

As given in below code, I store the state, and also I am getting values in the “value” variable after using onChange={(...)=>setValue1(...)}, value.target.ariaValueText.
My motive is I want to associate it with {key} mentioned in <Form.Lable>, so that I can store updated value along with the keys.

 const [value, setValue1] = React.useState(1);
 const handleChange=(changeEvent)=>{
 setValue1(prevState => {...prevState, [key]:changeEvent.target.value});
//console.log(key);
 console.log(prevState.key);
};

 return <div className={classes.root}>
        <Form.Label> {key} </Form.Label>
        <Slider
          
          defaultValue={dict[key]}
          aria-labelledby="discrete-slider-custom"
          getAriaValueText={valuetext}
          valueLabelDisplay="auto"
          //getAriaValueText={valuetext}
          //value={dict[key]}
          step={0.01}
          min={min1}
          max={max1}

          //onChange={} // for example updating a state value
          //onChangeCommitted={} // for example fetching new data

          //marks={marks_arr[i]}
         
          //onChange={handleChange}
          onChange={(changeEvent) =>
             setValue1(changeEvent.target.value)
          }
        
        />
       </div>
    })
    }
    </Form.Group>

Advertisement

Answer

You can update your type to be an object type to store key-value pairs. for eg:

 const [value, setValue1] = React.useState({});

 ...


 setValue1({[key]: changeEvent.target.value});
 // ---------^ this will create/update attribute with value of "key" in your state

If you have multiple sliders you’d have to do something like

setValue1(prevState => {...prevState, [key]: changeEvent.target.value});

to not lose other key-value pairs

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement