Bojan
Bojan

Reputation: 140

Gatsby SVG with <use> not working with gastby build

I created some SVG sprites/symbols to be able to use icon as component and with gatsby develop and it works fine (img below).

Working example of SVG Sprites

Problem is when i try to build my Gatsby application with gatsby build SVG icons are not showing (img below).

Broken example with gatsby build

Anyone has idea what am I missing?

My Icon component:


import { IconTypes } from "./types";
import Icons from "./icons.svg";

interface Props {
  name: IconTypes;
  className?: string;
  width?: number;
  height?: number;
  fill?: string;
}

export const Icon: FC<Props> = ({ name, className, width, height, fill }) => {
  return (
    <svg className={className} width={width} height={height} fill={fill}>
      <use href={`${Icons}#${name}`} />
    </svg>
  );
};

Upvotes: 1

Views: 583

Answers (1)

Ferran Buireu
Ferran Buireu

Reputation: 29335

Using SVGs in Gatsby + React could be tricky. I would suggest using gatsby-plugin-react-svg since it controls all the fallbacks. In your gatsby-config.js:

plugins: [
  {
    resolve: "gatsby-plugin-react-svg",
    options: {
      rule: {
        include: /svg/ 
      }
    }
  }
];

Note that the including rule is a regular expression. It means that /svg/ folder is the folder path in all your project (i.e: if you have your SVGs inside /src/assets/svg in the plugin configuration must include only /svg/).

The rest of the configuration is similar to the one you've described:

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

// ...

<Icon />;

Upvotes: 1

Related Questions