'Inputing number between a range in React

I have two input fields of type number, one for minimum value and the other for maximum value. At any given time user can update these values, but the minimum value cannot be greater than maximum value and vice versa. These are my functions which I am calling on 'onChange' event of input:

function minValUpdateHandler(e) {
  setMin((prevVal) => {
  const valInNum = +e.target.value;
  if (valInNum < max) {
    return valInNum;
  }
   return prevVal;
 });
}

function maxValUpdateHandler(e) {
  setMax((prevVal) => {
  const valInNum = +e.target.value;
  if (valInNum > min) {
    return valInNum;
  }
  return prevVal;
 });
}

And this is the codesandbox link for the POC. Please assist me with this.

Thanks



Solution 1:[1]

the problem was the type of value, the type of value is String so '9' can be bigger than '10' this code can solve the problem

parseInt(e.target.value,10); also, you can not set the min attribute from min input and either max for max input

I suggest using return max-1; instead of return prevVal and return min+1; instead of return prevVal

import "./styles.css";

export default function App() {
  const [min, setMin] = useState(0);
  const [max, setMax] = useState(100);

  function minValUpdateHandler(e) {
    setMin((prevVal) => {
      const valInNum = +parseInt(e.target.value);
      if (valInNum < max) {
        return valInNum;
      }
      return max-1;
    });
  }

  function maxValUpdateHandler(e) {
    setMax((prevVal) => {
      const valInNum = +parseInt(e.target.value);
      if (valInNum > min) {
        return valInNum;
      }
      return min+1;
    });
  }

  return (
    <div className="App">
      <h1>Min Max input</h1>
      <div className="inputContainer">
        <div>
          <label htmlFor="min">Min</label>
          <input
            type="number"
            id="min"
            value={min}
            max={max - 1}
            onChange={minValUpdateHandler}
          />
        </div>
        <span>-</span>
        <div>
          <label htmlFor="max">Max</label>
          <input
            type="number"
            id="max"
            value={max}
            min={min + 1}
            onChange={maxValUpdateHandler}
          />
        </div>
      </div>
    </div>
  );
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1