Reputation: 289
I am trying to implement a range slider into my React app but when I type in the code, the slider does not work at all?
It doesn't drag side to side. Clicking on it also does not move it. Although, if I use the exact same code on codepen, the slider works completely fine.
I have tried researching this but I cannot find a clear answer. Anybody have any idea what can be wrong?
The code in question:
<input
type="range"
min="1"
max="100"
value="50"
class="slider"
id="myRange"
/>
Here is my app in its entirety.
import "./App.scss"
import React, { useState } from "react"
function App() {
const [firstColorInput, setFirstColorInput] = useState("")
const [secondColorInput, setSecondColorInput] = useState("")
const [mode, setMode] = useState("single")
const handlefirstColorChange = (e) => {
setFirstColorInput(e.target.value)
console.log(firstColorInput)
}
const handlesecondColorChange = (e) => {
setSecondColorInput(e.target.value)
console.log(secondColorInput)
}
return (
<div
className="App"
style={{
background:
mode === "single"
? firstColorInput
: `linear-gradient(${firstColorInput}, ${secondColorInput})`,
}}
>
<div class="container">
<div id="colour_picker">
<input
type="text"
onChange={handlefirstColorChange}
value={firstColorInput}
id="input_first"
placeholder={
mode === "single"
? "Enter color name or code"
: "Enter First Colour"
}
class="inputs"
/>
<input
type="text"
onChange={handlesecondColorChange}
value={secondColorInput}
style={{ display: mode === "single" ? "none" : "block" }}
id="input_second"
placeholder={mode === "single" ? "" : "Enter Second Colour"}
class="inputs"
/>
<button
onClick={() => setMode(mode === "single" ? "gradient" : "single")}
>
{mode === "single" ? "Single Colour" : "Gradient"}
</button>
<input
type="range"
min="1"
max="100"
value="50"
class="slider"
id="myRange"
/>
</div>
</div>
</div>
)
}
export default App
Upvotes: 1
Views: 2813
Reputation: 85102
value="50"
In react, this tells it to set the value to 50, and never change it.
You have two options: you can either run the input as an uncontrolled component, by giving it a default value:
defaultValue="50"
Or you can do it as a controlled component by having a state variable:
const [value, setValue] = useState("50");
//...
<input
type="range"
min="1"
max="100"
value={value}
onChange={(e) => setValue(e.target.value)}
class="slider"
id="myRange"
/>
If you're not sure which one you need, do the controlled version. For more information on the difference between controlled and uncontrolled components, see this page and this page
Upvotes: 3