1

I have created two boxes, one with the css module scheme and the other with styled-components. However, the transition will fail on the box created with styled-components, but not on the box created with the css modules scheme. I have added a button to demonstrate the difference.

import React, { useState } from "react";
import styled from "styled-components";
import "./App.css";

const App = () => {
  const [boxHeight, setBoxHeight] = useState(20);

  const Box = styled.div`
    border: 2px solid black;
    height: ${boxHeight}px;
    padding: 0 2rem;
    width: 4rem;
    transition: all 3s  linear;
  `;

  return (
    <div>
      <div
        className="box"
        style={{ border: "2px solid black", height: `${boxHeight}px` }}
      >
        box 1
      </div>
      <Box>box 2</Box>
      <button onClick={() => setBoxHeight(boxHeight + 100)}>+100</button>
    </div>
  );
};
/* App.css */

.box{
  border: 2px solid black;
  padding: 0 2rem;
  width: 4rem;
  transition: all 2s linear;
}

enter image description here

My guess is that when the style of a component created by styled-components changes, the component is destroyed and a new one is created with the changed style, rather than just modifying the component. I wonder if there is any good solution to use transition through styled-components .

bearbaba
  • 23
  • 3

1 Answers1

0

Thanks to my colleague, now I know that I should create the component created by styled-components outside of another component. If it is created inside the component, it will be recreated every time it is rendered.

import React, { useState } from "react";
import styled,{css} from "styled-components";
import "./App.css";


const Box = styled.div`
  ${props=>css`
    height: ${props.height}px;
  `}
  border: 2px solid black;
  padding: 0 2rem;
  width: 4rem;
  transition: all 3s linear;
`;

const App = () => {
  const [boxHeight, setBoxHeight] = useState(20);


  return (
    <div>
      <div
        className="box"
        style={{ border: "2px solid black", height: `${boxHeight}px` }}
      >
        box 1
      </div>
      <Box height={boxHeight}>box 2</Box>
      <button onClick={() => setBoxHeight(boxHeight + 100)}>+100</button>
    </div>
  );
};

export default App;
bearbaba
  • 23
  • 3