React에서 svg를 다루는 패턴들 (feat. react-component)

udin·2024년 7월 29일

React에서 SVG를 표시하는 방법은 여러가지가 있다.

1. svg를 import하여 img 태그로 표현

import Pohang from '@/assets/images/pohang.svg?react';

export const Component = () => {
  return (
     <img src={Pohang} />
  )
}

2. svg를 컴포넌트화하고 import하여 사용

수동 패턴

❶ Logo svg를 컴포넌트화

export const Logo = ({width, height}) => {
  // width , height 초기화 로직
  return (
    <svg width={wrapperWidth} heigt={wrapperHeight} viewBox={}>
      <rect>
        ...
      </rect>
    </svg>
  )
}

❷ 필요한 페이지 혹은 컴포넌트에서 import하여 사용

import Logo from './Logo.svg';

export const Header = () => {
  return (
     <Logo width={80} height={80} /> 
  )
}

자동 패턴

svgr이라는 svg파일을 리액트 컴포넌트로 변환시켜주는 라이브러리를 사용한다.
프로젝트에서 사용하는 번들러에 따라 설정방법이 달라진다.

  • webpack ➔ svgr 바로 사용
  • vite ➔ svgr의 vite 지원 플러그인 vite-plugin-svgr을 별도로 사용

vite의 기준으로 설명하자면

❶ vite-plugin-svgr 을 설치

# npm
npm install --save-dev vite-plugin-svgr

# yarn
yarn add -D vite-plugin-svgr

# pnpm
pnpm add -D vite-plugin-svgr

❷ vite.config.js / vite.config.ts에 플러그인 설정

import svgr from 'vite-plugin-svgr';

export default defineConfig({
  plugins: [
    ...
    svgr({
       // React 컴포넌트를 디폴트로 export한다면 true (default: true)
      exportAsDefault: true,
      // 어떤 파일들이 SVGR 플러그인에 의해 처리될지를 지정
      include: '**/*.svg?react',
    }),
  ],
});

이 외에도 Export, esbuild 등 다양한 옵션을 지원한다.

      // Set it to `true` to export React component as default.
      // Notice that it will override the default behavior of Vite.
      exportAsDefault: false,

      // svgr options: https://react-svgr.com/docs/options/
      svgrOptions: {
        // ...
      },

      // esbuild options, to transform jsx to js
      esbuildOptions: {
        // ...
      },

      //  A minimatch pattern, or array of patterns, which specifies the files in the build the plugin should include. By default all svg files will be included.
      include: '**/*.svg',

      //  A minimatch pattern, or array of patterns, which specifies the files in the build the plugin should ignore. By default no files are ignored.
      exclude: '',
  • include:
    어떤 파일들이 SVGR 플러그인에 의해 처리될지를 지정한다.
    현재 '*/.svg?react'로 설정했기 때문에, 필요로하는 곳에서 import 시 경로에 .svg?react를 붙여야 svgr로 처리가 된다.

    예시

    • icon.svg?react → SVGR로 처리됨 (React 컴포넌트로 변환됨)
    • icon.svg → SVGR로 처리되지 않음 (일반적인 SVG 파일로 처리됨)

이 설정을 통해 특정 SVG 파일들만 React 컴포넌트로 변환하고, 나머지 SVG 파일들은 일반적인 이미지 파일로 사용한다.

❸ import 예시

├── src
│   ├── assets
│   │   ├── logo.svg
│   └── ...
└── package.json 
import Logo from '@/assets/images/logo.svg?react';

export const Header = () => {
  return (
     <Logo width={80} height={80} /> 
  )
}

0개의 댓글