Sometimes, we want to get the HTML5 input slider working in React.
In this article, we’ll look at how to get the HTML5 input slider working in React.
Get the HTML5 Input Slider Working in React
To get the HTML5 input slider working in React, we either set the value
and onChange
props or we can leave them both out.
For instance, we can write:
import React, { useState } from "react";
export default function App() {
const [value, setValue] = useState(0);
return (
<input
type="range"
min="0"
max="5"
value={value}
onChange={(e) => setValue(e.target.value)}
step="1"
/>
);
}
We add the value
prop and set it to the value
state.
And we set the onChange
prop to a function that calls setValue
with e.target.value
, which has the selected number value.
This makes the range slider a controlled component which means its value is controlled by a state.
We can also leave them both out if we don’t want to bind the value of the range slider to a state.
This would make it an uncontrolled input.
Conclusion
To get the HTML5 input slider working in React, we either set the value
and onChange
props or we can leave them both out.