Home > OS >  Why when I import an SVG into React, are all the group elements removed?
Why when I import an SVG into React, are all the group elements removed?

Time:12-07

I've tried using both the babel plugin babel-plugin-inline-react-svg, and the Webpack loader @svgr/webpack - but after successfully importing my SVG into React, all of the group elements are removed.

i.e. I can import either as...

import MySVG from '../assets/images/mysvg.svg'

or

import { ReactComponent as MySVG } from '../assets/images/mysvg.svg'

In my sourve SVG file, each of my group element has an ID attribute that I was planning on using to animate parts of the SVG via a styled component, for example

<g id="foo"><path..../></g>

...but all of the <g> elements are being removed!

I'm exporting the SVG from Adobe Illustrator, with layer names as the group IDs. I'm currently testing this with the latest version of Next.js

Thoughts?

CodePudding user response:

Okay took a little digging into the SVGR docs...

https://github.com/svg/svgo

  1. add the following to the next.config.js file...
webpack(config) {
    config.module.rules.push(
      {
        type: 'asset',
        resourceQuery: /url/, // *.svg?url
      },
      {
        test: /\.svg$/i,
        issuer: /\.[jt]sx?$/,
        use: ['@svgr/webpack'],
      }
    )

    return config
  },
  1. then create an svgo.config.js file, and place it in the root of your next.js project, with the following options...
// https://github.com/svg/svgo
module.exports = {
  svgo: true,
  plugins: [
    {
      name: 'preset-default',
      params: {
        overrides: {
          // or disable plugins
          cleanupIDs: false,
          prefixIds: false,
        },
      },
    },
  ],
}

CodePudding user response:

#If the immage in the asset directory is mysvg.svg

import mysvg from "../assets/images/mysvg.svg";

  • Related