Search code examples
javascriptreactjsstyled-components

styled-components makes input range not work


  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


Solution

  • Issue

    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.

    Solution

    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>
      );
    }
    

    Edit styled-components-makes-input-range-not-work