Handle SVG images in React components in a Gatsby project

ReactJS|SEPTEMBER 22, 2024|3 VIEWS
To properly handle SVG images in a Gatsby project, you can use the gatsby-plugin-react-svg plugin

This plugin allows you to import SVG files as React components, which provides more flexibility and control over the SVGs. Here’s how you can set it up and use it

Install plugin

npm install gatsby-plugin-react-svg

Create assets folder to locate your svg files

Create assets/svg folder inside src folder

Create example.inline.svg file inside above folder

Note: You need to name SVGs used in React components like example.inline.svg and process them with svg-react-loader

Configure the Plugin in gatsby-config.ts:

module.exports = {
  plugins: [
    // other plugins
    {
      resolve: 'gatsby-plugin-react-svg',
      options: {
        rule: {
          include: /\.inline\.svg$/
        }
      }
    }
  ],
};

Usage

import React from "react";
import ExampleIcon from "path/to/assets/svg/example.inline.svg";

const Component = () => {
  return (
    <div>
        <ExampleIcon className="w-6 h-6" />
    </div>
  );
};

export default Component;

Using with typescript

Create a declarations.d.ts file in your src folder to declare the module for SVG files.

declare module "*.svg" {
  const content: any;
  export default content;
}

Use it in your TS component

import React from "react";
import ExampleIcon from "path/to/assets/svg/example.inline.svg";

const Component = () => {
  return (
    <div>
        <ExampleIcon className="w-6 h-6" />
    </div>
  );
};

export default Component;

So that's it. Enjoy your day!