공부 및 일상기록

[trouble-shooting] styled-components에서 keyframe 변수 공유 문제 본문

개발/TIL WIL 공부목표

[trouble-shooting] styled-components에서 keyframe 변수 공유 문제

낚시하고싶어요 2023. 6. 21. 02:17

면접 과제로 간단한 차트와 애니메이션 구현등의 기능이 포함되어야 한다고 해서 나는 둘을 합쳐서 구현했다.

 

정말 간단하게 svg를 이용해서 차트를 만들었고, keyframe을 이용해서 구현하였다.

 

props를 통해서 data를 넘겨주면 해당 비율만큼 채워지는 Pie Chart를 구현했다.

 

무난하게 작성 완료 후, 나는 정답 차트와 오답 차트가 필요해서 해당 컴포넌트를 두번 불러서 다른 data를 넘겨주는 방식을 택했다.

 

그런데 여기서 문제가 발생했다.

 

서로 다른 비율의 data를 넘겨줘도 이상하게 차트는 똑같이 그려지는 문제였다.

서로 다른 비율을 표시하지만 같은 길이만큼 차트가 생성됨

 

1.  오답코드

const Circle = styled.circle`
  transform: rotate(-90deg);
  transform-origin: 50% 50%;
  stroke-dasharray: ${(props) => props.circum};
  stroke-dashoffset: ${(props) => props.circum};
  stroke: blue;
  stroke-width: 10;
  cx: 50;
  cy: 50;
  animation: line 2s forwards;
  @keyframes line {
    from {
      stroke-dashoffset: ${(props) => props.circum};
    }
    to {
      stroke-dashoffset: ${(props) => props.dashOffset};
    }
  }
`;

먼저 위의 문제가 발생한 오답 코드이다.

내가 간과했던것은 css keyframes는 전역적으로 생성되어 중복된 이름을 사용할 수 없는 것이다.

 

따라서 정답 컴포넌트와 오답 컴포넌트는 서로 다른 데이터를 가지고 있지만 결국 같은 keyframes이기 때문에 같은 길이를 보여주고 있던 것이였다.

 

2. 정답코드

import { keyframes } from "styled-components";

const lineKeyframe = (circum: number, dashOffset: number) => keyframes`
    from {
      stroke-dashoffset: ${circum};
    }
    to {
      stroke-dashoffset: ${dashOffset};
    }
`;

const Circle = styled.circle<ICircleProps>`
  transform: rotate(-90deg);
  transform-origin: 50% 50%;
  stroke-dasharray: ${(props) => props.circum};
  stroke-dashoffset: ${(props) => props.circum};
  fill: #e1dede;
  stroke: ${(props) => (props.lineColor === "success" ? "#5353d7" : "#d75353")};
  stroke-width: 6;
  stroke-linecap: round;
  cx: 50;
  cy: 50;
  animation: ${(props) => lineKeyframe(props.circum, props.dashOffset)} 1s
    forwards;
`;

해결한 방법은 styled-components에서 지역 scope로 keyframes 사용할수 있도록 모듈을 제공해주는데 해당 모듈을 이용하는 것이였다.

 

위 코드와 같이 keyframes라는 모듈을 가져와서 사용하면 해당 스코프에서만 사용가능한 keyframes를 만들 수 있게 되어, 두 컴포넌트는 아예 독립적인 컴포넌트가 된다.

해결됨!