react-svg 이용해서 next.js에서 svg 편하게 이용하기 (emotion, storybook)

wiz·2022년 4월 23일
0

배경

  • 색상을 emotion theme 를 이용해서 동적으로 지정하고 싶다
  • 사이즈를 동적으로 지정하고 싶다
  • 새로운 icon svg 파일이 추가될 때마다 해야할 작업을 최소화하고 싶다
  • 여러가지 설정이 귀찮다

과정

react-svg 을 이용하기로 했다

결과

yarn add react-svg

componenets/icon.tsx

import {useTheme} from "@emotion/react"
import React from "react"
import {ReactSVG} from "react-svg"

export type IconProps = {
  name: IconName
  color?: string
  size?: number
}

export type IconName = "arrow-back" | "arrow-right"

export const Icon = ({
  color,
  size = 24,
  name,
}: IconProps) => {
  const theme = useTheme()
  
  const handleBeforeInjection = (svg: SVGSVGElement) => {
    if (!svg) return;

    svg.setAttribute("width", size.toString());
    svg.setAttribute("height", size.toString());
  }

  const reactSvgStyle = {
    color: "inherit",
    fontSize: 0,
  }

  return (
    <span css={{
      color: color ? color : theme.colors["grey-90"],
    }}>
      <ReactSVG
        src={`/icons/${name}.svg`}
        beforeInjection={(handleBeforeInjection)}
        style={reactSvgStyle}
      />
    </span>
  )
}

public/icons/arrow-right.svg

동적으로 색상을 지정하고 싶은 부분에 currentColor 를 넣는다 (fill이든 stroke 이든)

<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M9.33333 18L15.1399 12.9192C15.5952 12.5208 15.5952 11.8125 15.1399 11.4141L9.33333 6.33333" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

storybook 에서 이용할 때 주의점

package.json 의 storybook 코맨드에 public path 설정해줘야 한다

  • "storybook": "start-storybook -s ./public -p 6006",
profile
성장 중인 프론트엔드 개발자

0개의 댓글