L
L
LeroViten2021-11-12 16:19:54
React
LeroViten, 2021-11-12 16:19:54

How to create two dependent inputs of type range (slider) with a jagged step in React?

1) Create 2 inputs type range;
2) The first input takes a value in thousands with a step of 1000 from 1 to 20
(allowable input values ​​are 1000,2000....10000,20000, but not 19500)
3) The second input takes a value in units. The step is uneven 3-7-14-54-70 (valid values ​​are 3-7-14-54-70
, but not 55 or 68) slider must be 54 or greater and cannot be moved down. 5) If the value is less than 10,000 on the upper slider, then you can move the lower slider to 3-7-14. But not 54 or 70. An example sandbox is here: Sandbox


Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-11-13
@LeroViten

Add the valid values ​​of the second input into an array:

const values = [ 2, 3, 5, 7, 11, 13, 17, 19, ... ];

Make an effect depending on both values, where the second one will be corrected. Take that half of the allowed values ​​of the second input, which corresponds to the current value of the first input, look for the closest to the current second input in it:
useEffect(() => {
  const index = values.indexOf(граничное_значение_второго_инпута);

  setVal2(values
    .slice(...(val1 > граничное_значение_первого_инпута ? [ index ] : [ 0, index ]))
    .reduce((val, n) => Math.abs(val - val2) < Math.abs(n - val2) ? val : n)
  );
}, [ val1, val2 ]);

https://jsfiddle.net/recx8j6w/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question