Categories
JavaScript Answers

How to Embed SVGs into React?

Spread the love

We can embed SVGs directly with JSX into our React app.

For instance, we can write:

import React from "react";

const SvgWithXlink = (props) => {
  return (
    <svg
      width="100%"
      height="100%"
      xmlns="http://www.w3.org/2000/svg"
      xmlnsXlink="http://www.w3.org/1999/xlink"
    >
      <style>{\`.classA { fill:${props.fill} }\`}</style>
      <defs>
        <g id="Port">
          <circle style={{ fill: "inherit" }} r="10" />
        </g>
      </defs>

      <text y="15">black</text>
      <use x="70" y="10" xlinkHref="#Port" />
      <text y="35">{props.fill}</text>
      <use x="70" y="30" xlinkHref="#Port" className="classA" />
      <text y="55">blue</text>
      <use x="70" y="50" xlinkHref="#Port" style={{ fill: "blue" }} />
    </svg>
  );
};

export default function App() {
  return (
    <div className="App">
      <SvgWithXlink fill="green" />
    </div>
  );
}

to embed the SVG in the SvgWithXLink component.

We just put the elements required to embed the SVG into the component.

And we can pass props into the elements as we do with any other HTML elements or components.

We have the circle to add circles.

And the xLinkHref attribute lets us the circle by the id of the g element.

x and y are the coordinates of the location of the elements.

In App , we add SvgWithXLink with the fill prop set to 'green' .

Now we see 3 circles.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *