//Quote.style.ts
import { css, keyframes } from "@emotion/react";
export const fadeInUp = keyframes`
from {
transform: translateY(60%);
opacity: 0;
}
to {
transform: translateY(0);
opacity: 1;
}
`;
export const quote = css`
font-size: 0.8rem;
padding: 0 0 0.5rem 0.2rem;
animation: ${fadeInUp} 0.5s ease-in-out;
`
//Quote.tsx
import { useEffect, useState } from "react";
import { quoteList } from '../../../constants/quoteList';
import { quote } from "./Quote.style";
const Quote = () => {
const [curIdx, setCurIdx] = useState(0);
useEffect(() => {
const interval = setInterval(() => setCurIdx(prev => (prev + 1) % quoteList.length), 5000);
return () => clearInterval(interval);
}, []);
return (
<section css={quote}>{quoteList[curIdx]}</section>
);
};
export default Quote;
위와 같이 작성해주었는데 animation이 작동되지 않았다.
React 컴포넌트에서 quoteList[curIdx]
가 변경될 때마다 <section>
요소가 새로 렌더링되어야하며, 이때마다 animation이 트리거되어야한다.
문제는 React가 DOM을 효율적으로 관리하려 할 때, 같은 내용의 요소는 다시 렌더링하지 않으려는 최적화가 발생할 수 있다는 점이다.
이를 해결하기 위해 key 속성을 사용하여 React에게 각각의 <section>
요소가 고유하다는 것을 알려줄 수 있다.
각 키가 고유할 때마다, React는 새 요소로 간주하고 animation을 다시 실행한다.
<section css={quote} key={curIdx}>{quoteList[curIdx]}</section>
위와 같이 수정하였더니 해결됐다.