Import SVG as a component in Gatsby

As you said, there are plugins to achieve this, which means a cleaner code (not the full SVG tag inlined in the component) with the same final result. Using gatsby-plugin-react-svg plugin you just need to import your SVG like this:

import Icon from "./path/assets/icon.svg";

To install, you only need to add the dependency using npm or yarn and in your gatsby-config.js use this snippet:

{
  resolve: 'gatsby-plugin-react-svg',
  options: {
    rule: {
      include: /assets/
    }
  }
}

Note that /assets/ is an including rule based on a regular expression so the value must be your SVG folder (i.e: /svg/) and must only contain .svg files. In other words, if your path is /images/svg/ your including rule can only contain /svg/ (you can also add the full path but you’ll need to escape slashes).

Afterward, you will need to style the SVG if their inline styles don’t apply.


If you want to follow the non-plugin approach you can simply use a React-based approach, just creating a component that returns the SVG:

export const YourSvgComponent = () => (
  <svg
    version="1.1"
    baseProfile="full"
    width="300"
    height="200"
    xmlns="http://www.w3.org/2000/svg"
  >
    <rect width="100%" height="100%" fill="red" />
    <circle cx="150" cy="100" r="80" fill="green" />
    <text x="150" y="125" font-size="60" text-anchor="middle" fill="white">
      SVG
    </text>
  </svg>
);

Now you just need to import it and use it.

Leave a Comment