[Next.js] SVG 파일 다루기

Date:

Updated:

Categories:

Tags: , ,


Next.js에서 SVG를 React Component로 다루는 방법

Next.js에서 SVG를 <Image> 컴포넌트로 불러오게 되면 색상과 같은 속성 제어가 어렵다. 이를 보완하기 위해서는 Webpack을 설정하여 사용하면 된다.

설치

$ npm i @svgr/webpack

Webpack 설정

  • next.config.ts
const nextConfig = {
  // ...
  webpack: (config) => {
    config.module.rules.push({
      test: /\.svg$/i,
      issuer: /\.[jt]sx?$/,
      use: ["@svgr/webpack"],
    });
    return config;
  },
};

적용

svg 파일의 fill, width 등 관련된 모든 속성들의 값을 "current"로 변경한 뒤, 필요한 컴포넌트에서 css를 적용해주면 된다.

  • Component.tsx
import Icon from "../assets/icon.svg";

const customStyles = {
  fill: "red",
};

function Component() {
  // ...
  return <Icon style={customStyles} />;
}