Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SVG in JSX - how to convert defs tag

Tags:

css

reactjs

jsx

svg

I have some SVGs that have a defs attribute with a style tags inside. Like this:

<svg ...>
  <defs>
    <style>.cls-1,.cls-7{fill:#b2488d;}.cls-1,.cls-2,.cls-3,.cls-4,.cls-5,.cls-6{stroke:#671f4d;}</style>
  </defs>
  ...
</svg>

I want to use these SVGs in React, so I want to convert them to valid JSX. I already used tools like svg2jsx, but they strip the defs tag away so none of the style attributes are present anymore. Is there a way to preserve the defs with the style tag inside by converting the SVG in JSX? Or is it not possible to use css classes in this case?

like image 989
feychu Avatar asked Oct 10 '17 15:10

feychu


People also ask

How do I use SVG DEFS?

The <defs> in SVG is used whenever we want a particular element to render only when required or when it is called. objects that are created inside <defs> element are not rendered directly they are needed to be called by <use> element to render them on the browser. Property values: It does not have any property values.

What is SVG in JSX?

SVG is a vector graphics image format based on XML. SVG stands for Scalable Vector Graphics. It was developed in the late 1990s and was poorly supported until around 2016. Today, a huge percentage of icon libraries, such as Flaticon, Font Awesome, Material Icon, etc., have full support for SVG.

Which SVG attributes are supported by React?

SVG is well-supported in modern browsers, including Firefox, Safari, Chrome, and Edge. All of these support embedding SVG directly in HTML, and React supports using SVG elements to build your components.


1 Answers

You can preserve the styles without any conversion. For that wrap all the CSS classes inside the style tag with {` and `}. Now your SVG becomes like this

<svg ...>
  <defs>
    <style>{`.cls-1,.cls-7{fill:#b2488d;}.cls-1,.cls-2,.cls-3,.cls-4,.cls-5,.cls-6{stroke:#671f4d;}`}</style>
  </defs>
  ...
</svg>

This will render without any problem.

like image 125
Nipun Avatar answered Sep 25 '22 00:09

Nipun