Home > Software engineering >  React: input slider trying to limit value of second slider to above first slider
React: input slider trying to limit value of second slider to above first slider

Time:08-25

I'm trying to implement 2 sliders where the 2nd sliders value cannot be lower than the 1st sliders value but the value of the 2nd slider seems to get stuck at around 9.xx when the 1st slider is moved passed this point for trimming videos. The 2 sliders are displayed in VidTrim.js. Overall it is working fine but I can't figure out why this bug is occurring especially around the same value so consistently. Any help would be appreciated.

example jsFiddle

VidTrim.js

function VidTrim() {
const useState = React.useState;
let end_slider_start = 0;

const [start_val, set_start_val] = useState(0);
const [end_val, set_end_val] = useState(0);

function onSlideChangeStart(event) {
  console.log(event.target.value);
  set_start_val(event.target.value);
  check_end_val(end_val);
  console.log("start: ", start_val);
  console.log("end: ", end_val);
  
}

function onSlideChangeEnd(event) {
  check_end_val(event.target.value);
}

function check_end_val(val) {
  if (val < start_val) {
    set_end_val(start_val);
  }
}

return (
<div className="VidTrim">
  <div>

    <div id="Sliders">
        <Slider value={start_val} title={"Start Trim"} changeSlide={onSlideChangeStart}></Slider>
        
        <Slider value={end_val} min={start_val} disabled={false} title={"End Trim"} changeSlide={onSlideChangeEnd}></Slider>
    </div>
  </div>
</div>);}

Sliders.js function Slider (props) {

function onChange(event) {
    this.props.changeSlide(event);
}

return (
    
<div className="Slider" style={{textAlign: 'center'}}>

    <h1 className='sliderTitle'>{props.title}</h1>
    <p >{props.value} seconds</p>
    <input value={props.value} step="0.01" min={0} max={100} type="range" onInput={props.changeSlide} style={{width: "100%"}} ></input>
</div>);}

CodePudding user response:

You can constrain the second slider like this:

const [start, setStart] = useState(0);
const [end, setEnd] = useState(0);

function onStartChange(val) {
  setStart(val);
  setEnd(Math.max(end, val));
}

function onEndChange(val) {
  setEnd(Math.max(val, start));
}

Working example

  • Related