코치코치

SVG 공통 컴포넌트 사용하기

합주기 2024. 10. 20. 00:54

하나의 SVG 파일로 색상, 사이즈를 변경하여 사용하기 위하여 공통 컴포넌트를 생성하였습니다.

우선 vite-plugin-svgr을 설치해야합니다.

 

[설치하는 법]

https://hazzuu.tistory.com/entry/vite-plugin-svgr%EB%A1%9C-%EC%95%84%EC%9D%B4%EC%BD%98-%ED%99%94%EB%A9%B4%EC%97%90-%EB%B3%B4%EC%97%AC%EC%A3%BC%EA%B8%B0

 

vite-plugin-svgr은 svg 파일을 컴포넌트로 만들어주는 플러그인입니다.

따라서 사용할 때도 컴포넌트 파일 임포트하는 것처럼 가져오면 되는데 주의할 점은 ?react를 붙여서 가져와야됨!

 

 

svg 파일을 하나 저장합니다.

변경하고자 하는 속성을 current로 변경합니다.

 

아이콘을 assets 상수 파일에서 관리하는 방식을 선택하였습니다. 이렇게 모든 아이콘 import를 한 곳에 모아두는 이유는 아이콘 디자인이 변경되었을 때 바로 해당 파일에서 수정할 수 있기 때문입니다.  

정리 : 각각 컴포넌트를 일일이 찾아야하는 불편함을 해소시켜줌

 

색상, 사이즈 등을 프롭스로 받는 공통 컴포넌트를 생성하였습니다.

이전에 styled-components에서 사용할 테마 파일을 만들어서 색상 팔레트를 구현하였습니다. 

팔레트에 있는 색상일 경우 => theme.color[색상 키] 

팔레트에 없는 색상일 경우 => 색상 값

 

이렇게 공통 컴포넌트로 SVG 아이콘을 관리하면서, current속성을 사용해 색상, 사이즈를 동적으로 변경할 수 있었습니다.

import { ICONS } from "@/constants/assets";
import { ColorKey, theme } from "@/style/theme";
import { HTMLAttributes } from "react";
import { styled } from "styled-components";

interface IconProps extends HTMLAttributes<HTMLDivElement> {
  name: keyof typeof ICONS;
  width?: string; // 너비
  height?: string; // 높이
  stroke?: ColorKey | string; // 테두리 색상
  fill?: ColorKey | string; // 채우기 색상
  isButton?: boolean; // 버튼 여부
}

const SvgIcon = ({
  name,
  width = "23px",
  height = "23px",
  stroke = "none",
  fill = "none",
  ...props
}: IconProps) => {
  const SelectedIcon = ICONS[name];

  const icStroke =
    stroke in theme.color ? theme.color[stroke as ColorKey] : stroke;
  const icFill = fill in theme.color ? theme.color[fill as ColorKey] : fill;

  const icon = (
    <SelectedIcon
      width={width}
      height={height}
      stroke={icStroke}
      fill={icFill}
    />
  );

  return <IconStyle {...props}>{icon}</IconStyle>;
};

const IconStyle = styled.div`
  display: flex;
  justify-content: center;
  align-items: center;
`;

export default SvgIcon;