[React] 리액트에서 svg 사용하는 방법 : img, ReactComponent, svgr

2025. 8. 1. 13:28·React
반응형

📍 img 태그 - src

import Icon from '@/assets/icons/icon.svg';

...
	<img src={Icon} alt="icon" />
...
  • import한 이미지를 단순히 img 태그에 사용한다
  • 간편하지만 svg 파일의 색상을 변경할 수 없다

 

📍 ReactComponent

import { ReactComponent as Icon } from '@/assets/icons/icon.svg';

...
	<Icon fill="red" />
...
  • svg를 컴포넌트화하면 색상을 변경할 수 있다.
<svg width="26" height="27" viewBox="0 0 26 27" fill="none" xmlns="http://www.w3.org/2000/svg">
	<path d="M14.3 3.81517C13.925 3.53389 13.4688 3.38184 13 3.38184C12.5312 3.38184 12.075 3.53389 11.7 3.81517L4.11667 9.50267C3.84758 9.70449 3.62917 9.96619 3.47874 10.267C3.32831 10.5679 3.25 10.8996 3.25 11.236V21.5277C3.25 22.1023 3.47827 22.6534 3.8846 23.0597C4.29093 23.4661 4.84203 23.6943 5.41667 23.6943H9.64167C9.95772 23.6943 10.2608 23.5688 10.4843 23.3453C10.7078 23.1218 10.8333 22.8187 10.8333 22.5027V17.1943C10.8333 16.6197 11.0616 16.0686 11.4679 15.6623C11.8743 15.2559 12.4254 15.0277 13 15.0277C13.5746 15.0277 14.1257 15.2559 14.5321 15.6623C14.9384 16.0686 15.1667 16.6197 15.1667 17.1943V22.5027C15.1667 22.8187 15.2922 23.1218 15.5157 23.3453C15.7392 23.5688 16.0423 23.6943 16.3583 23.6943H20.5833C21.158 23.6943 21.7091 23.4661 22.1154 23.0597C22.5217 22.6534 22.75 22.1023 22.75 21.5277V11.236C22.75 10.8996 22.6717 10.5679 22.5213 10.267C22.3708 9.96619 22.1524 9.70449 21.8833 9.50267L14.3 3.81517Z"
	fill="current"/>
</svg>
  • svg 파일에서 바꾸고자 하는 요소를 current로 바꿔야 커스텀이 가능하다.

 

📍 svgr

나는 vite를 사용하기에 vite를 사용하는 방법으로 소개하겠다.

vite 프로젝트에서 svg 파일을 React 컴포넌트처럼 import 할 수 있는 라이브러리를 사용한다.

 

🔨 세팅하기

  • 패키지 설치하기
yarn add -D vite-plugin-svgr

 

vite.config.js
import {defineConfig} from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';
import svgr from 'vite-plugin-svgr'; // 이 부분 추가

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    react(),
    svgr({ // 이 부분 추가
      svgrOptions: {
        icon: true,
      },
    }),
  ],
  resolve: {
    alias: [
      {find: '@', replacement: path.resolve(__dirname, 'src')},
      {
        find: '@components',
        replacement: path.resolve(__dirname, 'src/components'),
      },
    ],
  },
  server: {
    host: '0.0.0.0', 
    port: 5173,
  },
});

 

svg.d.ts
declare module '*.svg' {
  import * as React from 'react';

  export const ReactComponent: React.FC<React.SVGProps<SVGSVGElement>>;
  const src: string;
  export default src;
}

 

tsconfig.json
"include": ["src/**/*.ts", "src/**/*.tsx", "test/**/*.ts", "svg.d.ts"]

 

vite-env.d.ts
/// <reference types="vite/client" />
/// <reference types="vite-plugin-svgr/client" />

 

🔨 사용하기

svg import
  • svg 파일에서 수정하고 싶은 부분에 current를 써준다
    • 아래 예시에서는 width, height, fill에 해줬다
<svg width="current" height="current" viewBox="0 0 26 27" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M14.3 3.81517C13.925 3.53389 13.4688 3.38184 13 3.38184C12.5312 3.38184 12.075 3.53389 11.7 3.81517L4.11667 9.50267C3.84758 9.70449 3.62917 9.96619 3.47874 10.267C3.32831 10.5679 3.25 10.8996 3.25 11.236V21.5277C3.25 22.1023 3.47827 22.6534 3.8846 23.0597C4.29093 23.4661 4.84203 23.6943 5.41667 23.6943H9.64167C9.95772 23.6943 10.2608 23.5688 10.4843 23.3453C10.7078 23.1218 10.8333 22.8187 10.8333 22.5027V17.1943C10.8333 16.6197 11.0616 16.0686 11.4679 15.6623C11.8743 15.2559 12.4254 15.0277 13 15.0277C13.5746 15.0277 14.1257 15.2559 14.5321 15.6623C14.9384 16.0686 15.1667 16.6197 15.1667 17.1943V22.5027C15.1667 22.8187 15.2922 23.1218 15.5157 23.3453C15.7392 23.5688 16.0423 23.6943 16.3583 23.6943H20.5833C21.158 23.6943 21.7091 23.4661 22.1154 23.0597C22.5217 22.6534 22.75 22.1023 22.75 21.5277V11.236C22.75 10.8996 22.6717 10.5679 22.5213 10.267C22.3708 9.96619 22.1524 9.70449 21.8833 9.50267L14.3 3.81517Z"
    fill="current"/>
</svg>

 

  • svg 확장자 뒤에 ?react를 붙인다
    • fill, width, height를 설정해 준다
import Icon from '@/assets/icons/home-fill.svg?react';

...
	<Icon fill="#C3C3C3" width="26" height="26" />
...

 

 


 

[에러가 발생했다..]

에러 해결 과정 ⬇️

 

[React] svgr 세팅 - Duplicate identifier 'src'.

🚨 문제 상황svgr을 쓰기 위해 환경세팅을 하고 있었다.  global.d.tsdeclare module '*.svg' { import * as React from 'react'; export const ReactComponent: React.FC>; const src: string; export default src;}  위 파일의 마지막 src

allkong.tistory.com

 

 

[참고]

[React] vite + ts에서 vite-plugin-svgr로 svg 사용 설정

[React] Vite, TS 환경에서 SVGR을 사용해 SVG를 ReactComponent로 사용하기

[React] SVG 활용법

SVGR - Transforms SVG into React Components. - SVGR

반응형
'React' 카테고리의 다른 글
  • [React] toast 사용법 (react-toastify)
  • [React] 서명 패드 만들기 (react-signature-canvas)
  • [React] 리액트 특징 : 선언형 프로그래밍, Virtual DOM
  • [React] Control Props 패턴 : Controlled vs Uncontrolled
올콩
올콩
콩 심은 데 콩 난다
  • 올콩
    콩스토리
    올콩
  • 전체
    오늘
    어제
    • 분류 전체보기 (206) N
      • SSAFY (10)
      • Algorithm (120)
        • 이론 (6)
        • 백준 (BOJ) (112)
        • 프로그래머스 (1)
        • 코드트리 (1)
      • Trouble Shooting (10)
      • Frontend (7)
      • React (17)
      • Next.js (5) N
      • Vue (4)
      • Node.js (2)
      • HTML (9)
      • DevOps (4)
        • Git (4)
      • Language (9)
        • JavaScript (0)
        • Java (9)
      • Embedded (1)
      • CS (5)
        • Network (1)
        • Blockchain (4)
      • 자격증 (2)
      • 기타 (1)
        • Tistory (1)
  • 블로그 메뉴

    • GitHub
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    우선순위큐
    Error
    브루트포스
    SSAFY
    싸피
    Java
    티스토리챌린지
    dfs
    Next.js
    파이썬
    구현
    Algorithm
    중복순열
    알고리즘
    블록체인
    그리디
    React
    html5
    오블완
    SSAFYcial
    Heap
    백트래킹
    DP
    백준
    순열
    수학
    강의
    재귀
    힙
    bfs
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.5
올콩
[React] 리액트에서 svg 사용하는 방법 : img, ReactComponent, svgr
상단으로

티스토리툴바