I have created an input of type range using react with typescript. The problem I am facing is when I click on the increase/decrease button I have to click them twice then it will increase/decrease value. Sometimes when the value becomes a hundred the decrease button stop working.
Here is the code:
export default function App() {
const rangeRef = useRef<HTMLInputElement>(null);
const [rangeValue, setRangeValue] = useState<number>(0);
const updateRangeValue = () => {
const rangeRefference = rangeRef.current;
if (rangeRefference) {
const currentSilderLevel: number = (rangeRefference.value as unknown) as number;
setRangeValue(currentSilderLevel);
}
};
const increaseValue = () => {
const sliderValue = rangeValue 10;
setRangeValue(sliderValue);
};
const decreaseValue = () => {
const sliderValue = rangeValue - 10;
setRangeValue(sliderValue);
};
return (
<div className="App">
<button onClick={decreaseValue}>Decrease</button>
<input
type="range"
min="0"
max="100"
step="10"
onChange={updateRangeValue}
value={rangeValue}
ref={rangeRef}
/>
<button onClick={increaseValue}>Increase</button>
</div>
);
}
CodePudding user response:
this happens because your rangerValue goes beyond your 0-100 limit. and also you do not need to use refs for this. just use useState hook.
I have refactored your code.
import { useState } from "react";
import "./styles.css";
export default function App() {
const [rangeValue, setRangeValue] = useState<number>(0);
const increaseValue = () => {
let sliderValue = Math.min(rangeValue 10, 100);
setRangeValue(sliderValue);
};
const decreaseValue = () => {
let sliderValue = Math.max(0, rangeValue - 10);
setRangeValue(sliderValue);
};
const handleChange = (event: React.ChangeEvent) => {
const target = event.target as HTMLInputElement
setRangeValue(parseInt(target.value, 10))
}
return (
<div className="App">
<button onClick={decreaseValue}>Decrease</button>
<input
type="range"
min="0"
max="100"
step="10"
value={rangeValue}
onChange = {handleChange}
/>
<button onClick={increaseValue}>Increase</button>
</div>
);
}
check it out!
CodePudding user response:
What about setting the state like this ?
setRangeValue(prev => prev 10);
Ok I got it, you have put this props step="20" on your input, change it to step="10"