Next에서 svg 사용하는 방법

OwlSuri·2022년 8월 8일
1

next 환경에서 svg를 사용하려고 react svg를 검색해서 해봤지만 잘 안되었는데,
next에서 사용할 수 있는 방법이 따로 있었다.

설치

yarn add -D @svgr/webpack

next.config.js 수정

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  swcMinify: true,
  // 아래 부분 추가
  webpack: (config) => {
    config.module.rules.push({
      test: /\.svg$/i,
      issuer: /\.[jt]sx?$/,
      use: ["@svgr/webpack"],
    });
    return config;
  },
};

module.exports = nextConfig;

svg 가져오기

svg 파일 셋팅

/public/icons/right_arrow.svg

<svg width="20" height="20" viewBox="0 0 5 10" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M0.117062 9.26722C-0.0390211 9.43486 -0.039021 9.70664 0.117062 
9.87428C0.273145 10.0419 0.526206 10.0419 0.682289 9.87428L4.84392 5.4047C5.05203 5.18119 5.05203 
4.81881 4.84392 4.5953L0.682288 0.125724C0.526205 -0.0419079 0.273144 -0.0419079 0.117061 0.125724C-0.0390219 
0.293357 -0.0390218 0.565143 0.117061 0.732776L4.09028 5L0.117062 9.26722Z" 
fill="current"/>
</svg>

이렇게 생긴 svg 파일이 있다.
값을 받아서 쓰고 싶은 부분을 "current"로 바꾼다.
fill(색깔)을 바꿔서 여러곳에서 사용하고 싶어서 fill="current"로 바꿔주었다.

import

  • 사용하고 싶은 이름(BackIcon)을 적고, 파일의 경로를 찾아 import 한다.
  • react 컴포넌트 처럼 사용하면 된다.
  • current로 변경한 부분의 속성을 원하는 속성으로 준다.
import BackIcon from "../../public/icons/right_arrow.svg";
...
return(
 <BackIcon fill="black" />
)


하나의 svg 파일로 이렇게 색깔이 다르게 사용할 수 있다.
활용도가 아주 높을 것 같은 svg....!!
😄

참고 | https://kyounghwan01.github.io/blog/React/handling-svg/#next%E1%84%8B%E1%85%A6%E1%84%89%E1%85%A5-svg-%E1%84%89%E1%85%A1%E1%84%8B%E1%85%AD%E1%86%BC%E1%84%92%E1%85%A1%E1%84%80%E1%85%B5

profile
기억이 안되면, 기록을 -

0개의 댓글