Search code examples
reactjstypescriptstyled-components

React typescript pass value from slider to styled-component


I have a demo here

Its a simple react app with typescript.

I have a slider that outputs a value using useState

I need to use this value in a styled-component

So as the slider moves the height of the div will change.

I'm not getting errors in the code but its just not working.

Can anyone see what I'm doing wrong.

import React, { useState } from 'react';
import { render } from 'react-dom';
import './style.css';
import styled, { css } from 'styled-components';

const App = () => {
  const [value, setvalue] = useState<number>(300);

  const handelValue = (e: any) => {
    setvalue(e.target.value);
  };

  const Block = styled.div`
    background: red;
    width: 200px;
    //height: 200px;
    ${props =>
      props.value &&
      css`
        height: ${props.value};
      `}
  `;

  return (
    <div>
      <div>
        <input type="range" min="300" max="700" onChange={handelValue} />
      </div>
      {value}
      <Block {...value} />
    </div>
  );
};

render(<App />, document.getElementById('root'));

Solution

  • This is because when you {...value} you are spreading a number, where you should pass a value property to <Block />.

    Also, you can inspect in React Developer Tools that no property is passed to the styled div.

    The fixed version would be

    <Block value={value} />