in

How can I import an SVG as a component in Next.js?


I generally use Create React App and I am used to importing svgs like this:

import { ReactComponent as IconPerson } from '/icons/person.svg';

/src/icons/person.svg

<svg viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
  <path d="m8 8c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/>
</svg>

I’m trying out Next.js and when I try to do this I get this error:

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it’s defined in, or you might have mixed up default and named imports.

I was under the impression Next.js uses Create React App under the hood, so I expected this to work.

Do I need to wrap the SVG in a function like this?

export default function IconPerson() {
  return (
    <svg viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
      <path d="m8 8c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/>
    </svg>
  );
};

This isn’t ideal because it requires writing more code and it means I am unable to open the SVG in design software like Sketch.

Is there a way I can use the .svg file directly?

Note that I don’t want an <img> tag. I want the SVG markup on the DOM.



Source: https://stackoverflow.com/questions/70537800/how-can-i-import-an-svg-as-a-component-in-next-js

Failed loading page (Frame load interrupted by policy change)

Predict the stock market with AI