svgr icon indicating copy to clipboard operation
svgr copied to clipboard

How to use className inside SVG

Open amitsarkerr opened this issue 2 years ago • 4 comments

Hello,

I want to use className inside svg.

<svg xmlns="http://www.w3.org/2000/svg">
    <path className="logo-icon-blue" d="1h-65.71l-33.98,33.89Z"></path>
    <path className="logo-icon-red" d="m46.79,138.71c-."></path>
</svg>

Thanks in advance!

amitsarkerr avatar Sep 22 '23 19:09 amitsarkerr

Hello @amitsarkerr can you clarify your request, it is not clear enough for us to help you.

gregberge avatar Sep 24 '23 07:09 gregberge

I want to style svg elements using CSS.

SVG

<svg xmlns="http://www.w3.org/2000/svg">
    <path class="logo-icon-blue" d="1h-65.71l-33.98,33.89Z"></path>
    <path class="logo-icon-red" d="m46.79,138.71c-."></path>
</svg>

I import the svg and show on a component using <Logo />.

CSS
.logo-icon-blue {
fill: blue;
}
.logo-icon-red {
fill: red;
}

But, the css does not working. Because, logo-icon-blue this generate like svg__logo-icon-blue. Any suggestion how I can get the class name?

amitsarkerr avatar Sep 24 '23 09:09 amitsarkerr

@amitsarkerr That's probably SVGR+SVGO mangling the class attrs.

I prefer to have good SVG src to start, and so I always disable SVGO. That sidesteps the problem. If that would work for you,, you can add this to package.json. If not, #680 might have other approaches.

"svgr": {
  "svgo": false
},

For what little it's worth, having SVGR use a default/off the shelf config that rewrites src in a fundamentally breaking way feels off to me. Least surprise principle and all that. :)

ylg avatar Nov 08 '23 15:11 ylg

HI @amitsarkerr, just came across this issue. I wondered the same a couple of months ago and the problem is the following stated in the svgr documentary:

NOTE: SVGR implicitly enables the prefixIds SVGO plugin which adds a prefix to values of id and class attributes to reduce the chance of collision issues.

How to disable this behaviour?

  1. Create a svgo config file in your root called svgo.config.js
  2. Disable the prefixIds plugin:
module.exports = {
  plugins: [
    {
      name: "prefixIds",
      params: {
        prefixIds: false,
        prefixClassNames: false,
      },
    },
  ],
};

nikolailehbrink avatar Feb 01 '24 11:02 nikolailehbrink