🐡

Next.js(React)で SVG 画像を扱う方法

に公開

SVG 画像を扱う 3 つの方法

Next.js で SVG を扱う主な方法は以下の 3 つ:

  1. インラインスタイル(ハードコーディング)
  2. Image(img)タグを使用して外部ファイルとして読み込む
  3. svgr などのライブラリを使ってコンポーネント化する

1. インラインスタイル(ハードコーディング)

SVG のコードを直接 JSX 内に記述する方法。無駄にコード長くなるので、あえて選ぶ必要はない。

const Component = () => {
  return (
    <div>
      <svg
        width="20"
        height="20"
        viewBox="0 0 20 20"
        fill="none"
        xmlns="http://www.w3.org/2000/svg"
      >
        <path
          d="M16.61 4.32l-9.55 9.55-2.17-2.17a.5.5 0 00-.7.7l2.55 2.5a.5.5 0 00.7 0l9.9-9.9a.5.5 0 10-.7-.7h-.03z"
          fill="currentColor"
        />
      </svg>
    </div>
  );
};

2. Image(img)タグを使用する方法

Next.js のImageコンポーネントや通常のimgタグを使用して、SVG ファイルをパスで指定する方法。
一番基本的な表示方法。

import Image from "next/image";

const Component = () => {
  return (
    <Image
      src="/pencil.svg"
      className="hover:bg-[#B8B8B8] rounded-full"
      alt="edit"
      width={20}
      height={20}
    />
  );
};

3. svgr などのライブラリを使ったコンポーネント化

SVG を React コンポーネントとして扱えるようにする方法。svgr 系(@svgr/webpack, @svgr/cli)などのライブラリを使用する。
複数のページで使い回すような svg 画像ならこっちの方がいいかも。

設定例(Next.js の場合):

// next.config.js
module.exports = {
  webpack(config) {
    config.module.rules.push({
      test: /\.svg$/,
      use: ["@svgr/webpack"],
    });
    return config;
  },
};

型定義ファイルの例:

// index.d.ts
declare module "*.svg" {
  import type { FC, SVGProps } from "react";
  const content: FC<SVGProps<SVGSVGElement>>;
  export default content;
}

使用例:

import Pencil from "../../../../../public/pencil.svg";

const Component = () => {
  return <Pencil className="hover:bg-[#B8B8B8]/20 rounded-full" />;
};

 
 
 
 

以上です。

KA projects

Discussion