drag & drop을 styled-components로 제작도중 갑자기 속도가 느려지면서 다음 경고문이 발생했다.
Over 200 classes were generated for component styled.div with the id of "sc-jwKbUx".
Consider using the attrs method, together with a style object for frequently changed styles.
Example:
const Component = styled.div.attrs(props => ({
style: {
background: props.background,
},
}))`width: 100%;`
문제의 원인
원인은 drag & drop에서 props를 이용하여 left, top을 설정중인데, props 값이 바뀔때마다 styled-components는 새로운 클래스를 만들어낸다. drag&drop으로 이리저리 끌고다니니 무수히 많은 클래스가 생성되며 느려진 것...!
const Menus = styled.div<{ leftPosition: number; topPosition: number }>`
position: absolute;
left: ${(props) =>
props.leftPosition && `${props.leftPosition.toString()}px`};
top: ${(props) =>
props.topPosition && `${props.topPosition.toString()}px`};\
`
해결방법
공식문서와 에러메시지에서 해결방법을 제시하고 있다.
이렇게 매우 동적으로 변하는 스타일의 경우 attr 속성을 사용할 것.
attr은 직접 인라인 스타일에 적용하는 방법으로 클래스를 찍어내지 않고 바로 적용된다.
const Menus = styled.div.attrs<MenuPosition>((props) => ({
style: {
left: `${props.leftPosition.toString()}px`,
top: `${props.topPosition.toString()}px`,
},
}))<MenuPosition>`
position : absolute;
`;
You can pass in attributes to styled components using attrs, but it is not always sensible to do so.
The rule of thumb is to use attrs when you want every instance of a styled component to have that prop, and
pass props directly when every instance needs a different one:
다만, 공식문서에서 attr이 항상 합리적이지 않을 수 있다 표시한다.
제작자의 경험상 attr은 style이 매우 유동적으로 변할 때 사용하라 조언한다.
참고자료
styled-components 공식문서 : https://styled-components.com/docs/faqs#when-to-use-attrs
styled-components github issue : https://github.com/styled-components/styled-components/issues/1212
'Frontned Development > FE 프로젝트 개발' 카테고리의 다른 글
[GITLAB] DISCORD 커스텀 알림 만들기 (0) | 2024.03.17 |
---|---|
Axios를 이용하여 formData 객체를 전송 시, 서버에 빈 객체가 전달되는 문제 (0) | 2023.08.06 |
FormData 에러 (console.log , boundary 미확인) (0) | 2023.08.06 |
API의 속성이 제한되는 현상 (CORS-safelisted response header, Access-Control-Expose-Headers) (0) | 2023.07.31 |
[프로젝트 세팅] gitignore.io를 이용하여 .gitignore 생성하기 (0) | 2023.01.10 |