[React] svg icon 컴포넌트화해서 사용하기

2024. 6. 4. 12:10
반응형

 

// iconList.tsx

const iconList = {
  search: (
    <path
      d="M22.6375 20.3661L18.4567 16.1853C19.6434 14.6919 20.3572 12.8057 20.3572 10.75C20.3572 5.91751 16.4397 2 11.6072 2C6.77469 2 2.85718 5.91751 2.85718 10.75C2.85718 15.5825 6.77469 19.5 11.6072 19.5C13.6629 19.5 15.5491 18.7862 17.0425 17.5995L21.2233 21.7803C21.3698 21.9268 21.5617 22 21.7536 22C21.9456 22 22.1375 21.9268 22.284 21.7803L22.6375 21.4268C22.9304 21.1339 22.9304 20.659 22.6375 20.3661ZM11.6072 17.5C7.88522 17.5 4.85718 14.472 4.85718 10.75C4.85718 7.02802 7.88522 4 11.6072 4C15.3291 4 18.3572 7.02802 18.3572 10.75C18.3572 14.472 15.3291 17.5 11.6072 17.5Z"
      fill="currentColor"
    />
  ),
...
}

export default iconList

 

// Icon.tsx

import { SVGAttributes, forwardRef } from 'react';
import iconList from './iconList';
import theme from 'styles/theme';

type IconProps = {
  name: keyof typeof iconList;
  size?: number;
  color?: keyof typeof theme.colors;
} & SVGAttributes<SVGElement>;

const Icon = forwardRef<SVGSVGElement, IconProps>(function Icon(
  { name, size = 24, color, ...props },
  ref,
) {
  return (
    <svg
      ref={ref}
      width={size}
      height={size}
      color={color ? theme.colors[color] : 'currentColor'}
      viewBox="0 0 24 24"
      fill="none"
      xmlns="http://www.w3.org/2000/svg"
      {...props}
    >
      {iconList[name]}
    </svg>
  );
});

export default Icon;

 

 

위에서 만든 Icon.tsx를 가져다 쓰는 page

// AnotherPage.tsx

...

<Icon name="search" />
반응형

BELATED ARTICLES

more