Fer-de-lance
Fer-de-lance

Reputation: 421

Prevent range slider from resetting if user clears input

I have a range slider with input boxes. So far I have it mostly working but I need the thumb sliders to not reset in the middle if the user clears the input from the boxes. If a user clears the input I want the slider to stay at their current position.

Sliders reset in the middle if user clears and input

Slider reset

Slider reset max value

Here is the CodeSandbox

Upvotes: 3

Views: 935

Answers (4)

Jay Lu
Jay Lu

Reputation: 1745

You can control the values of input and slide separately, that will be much more convenient and conforms to React's state control.

Code fragment sample

    const [min, setMin] = useState({ input: 0, slide: 0 });
    const [max, setMax] = useState({ input: 100, slide: 100 });

    const handleMaxChange = (e) => {
    const v = parseInt(e.target.value, 10);
    if (v) {
      if (v < min.input && !!min.input) {
        setMax({ input: min.input + 1, slide: min.slide + 1 });
      } else if (v > extremeMax) {
        setMax({ input: extremeMax, slide: extremeMax });
      } else {
        setMax({ input: v, slide: v });
      }
    } else {
      setMax((prev) => ({ ...prev, input: "" }));
    }
  };

Full code sample

Edit TextField selectionStart

Upvotes: 0

Ruben Verster
Ruben Verster

Reputation: 362

This is a bit of an advanced solution, but you can use debouce from lodash (or code your own debounce function, but use packages instead)

What you can do is have a debounce on the user input for the sliders On the 'onChange' for your input component, debounce updating the slider value in your state, and have a check that if the input is null/undefined/empty, then don't update the state :)

I'm taking a break at work, but if you need me to provide exact code, I can do so ^-^

Upvotes: 2

the Hutt
the Hutt

Reputation: 18418

You can simply setup the slider like this:

<MultiRangeSlider
      minVal={min ? min : 0}
      maxVal={max ? max : 0}
      ...
/>

Demo on CodeSandbox.

Upvotes: -1

Abdul Mahamaliyev
Abdul Mahamaliyev

Reputation: 866

it's not clear to me what you really want to do. Because let's say Min value is 40, and user clears the textbox with backspaces: first time, it's 4, the second time backspace is hit it will be empty. Do you want the slider stay at 40 or 4?

in any case, you can hold the value for previous state of min/max and if the new value of textbox is empty, don't update the slider state.

Upvotes: 0

Related Questions