Search code examples
javascriptcssreactjswebstyled-components

Using spread operator in Styled-Components


I'm new to React and React-Spring and practicing how to use it.
There's really basic code from React-Spring document, and I want to convert it using styled-components.
I converted code to styled-components but don't know how to change ...springs in styled-components.
Can I know how to apply it with using styled-components??

document code: codesandbox


import '/index.css'
import { useSpring, animated } from '@react-spring/web'

export default function MyComponent() {
  const springs = useSpring({
    from: { x: 0 },
    to: { x: 100 },
  })

  return (
    <animated.div
      style={{
        width: 80,
        height: 80,
        background: '#ff6d6d',
        borderRadius: 8,
        // don't know how to conver this part
        ...springs,
      }}
    />
  )
}

my code: codesandbox

import { useSpring, animated } from "@react-spring/web";
import styled from "styled-components";

export default function App() {
  const springs = useSpring({
    from: { x: 0 },
    to: { x: 100 }
  });

  return (
    <Spring>
      <animated.div className="box">hi</animated.div>
    </Spring>
  );
}

const Spring = styled.div`
  border: 3px solid black;

  .box {
    width: 80px;
    height: 80px;
    background: #ff6d6d;
    border-radius: 8px;
    //this part doesn't work
    ...springs;
  }
`;

Solution

  • Having styled components or not doesn't affect your code: you should still spread the springs object directly into <animated.div>.

    return (
      <Spring>
        <animated.div className="box" style={{ ...springs }} />
      </Spring>
    );
    

    If you truly want to offload all the styling to styled-components, you can create a new styled component that uses animated.div internally, i.e.:

    const SpringBox = styled(animated.div)`
      width: 80px;
      height: 80px;
      background: #ff6d6d;
      border-radius: 8px;
    `;
    

    Then you can update your template as such: but note that you are still spreading the springs in the JSX template and not passing it via styled components:

    return (
      <Spring>
        <SpringBox style={{ ...springs }} />
      </Spring>
    );
    

    Edit spring-forest-l5opvz