Reputation: 237
const Input = styled.input`
display: block;
`;
const [slider, setSlider] = useState(25);
const onSlide = (e) => {
setSlider(e.target.value);
};
When I return
<input type="range" name="slider" min="1" max="60" value={slider} onChange={onSlide}/>
It works
<Input type="range" name="slider" min="1" max="60" value={slider} onChange={onSlide}/>
The slider does not slide anymore I don't understand why
Upvotes: 1
Views: 1238
Reputation: 203061
You've probably defined the styled Input
within your render function. It should be defined externally.
Define Styled Components outside of the render method
It is important to define your styled components outside of the render method, otherwise it will be recreated on every single render pass. Defining a styled component within the render method will thwart caching and drastically slow down rendering speed, and should be avoided.
Define Input
outside of any render function.
Remember, the entire body of a functional component is the render function.
const Input = styled.input`
display: block;
`;
function App() {
const [slider, setSlider] = useState(25);
const onSlide = (e) => {
setSlider(e.target.value);
};
return (
<div className="App">
...
<Input
type="range"
name="slider"
min="1"
max="60"
value={slider}
onChange={onSlide}
/>
...
</div>
);
}
Upvotes: 1
Reputation: 325
I made a sandbox with the code below and it works. I gave input a classname called slider.
import React, { useState } from "react";
import styled from "styled-components";
const Styles = styled.div`
.slider {
display: block;
}
`;
const App = () => {
const [state, setState] = useState(100);
const handleOnChange = (e) => {
setState(e.target.value);
};
return (
<Styles>
<input
type="range"
min={0}
max={255}
value={state}
className="slider"
onChange={handleOnChange}
/>
<div className="value">{state}</div>
</Styles>
);
};
export default App;
Upvotes: 0