Ricardo Sanchez
Ricardo Sanchez

Reputation: 5157

Get SVG from react-icons components

I need to get the svg element from a react-icon component to render the image using a different Javascript library.

I'm using paperjs as the drawing engine for this demo I'm working on, for the UI I use react-icons and react-bootstrap. Now paperjs allows to importSVG images, so I try the following:

import { MdMemory } from "react-icons/md";

const addDevice = () => {
  const svgGroup = Paper.project.importSVG(<MdMemory />);
  svgGroup.position = pointA.clone();
}

But when I do so I get the following error: Error: Unsupported SVG source: [object Object]

When I inspect the other place where I use <MdMemory /> I get an svg element, so I wonder if what I'm trying to achieve is possible as I don't want to load duplicated assets.

UPDATE

After spending a bit more time, I came up with the following:

console.log(MdMemory().props.children[0].props.d);
const svgGroup = Paper.project.importSVG(`<svg><path d=${MdMemory().props.children[0].props.d}></path></svg>`);

Where MdMemory().props.children[0].props.d is the actual svg path, but I'm still unable to render anything...

Upvotes: 2

Views: 5114

Answers (3)

Saroj Ghalan
Saroj Ghalan

Reputation: 31

I just searched for the icon on React Icons and inspected that icon through console, and then I copied and pasted it:

  • Browser

    browser

  • Copying

    copying

  • Paste

    pasting

Upvotes: 2

Tovi Newman
Tovi Newman

Reputation: 715

This worked better for me:

ReactDOMServer.renderToString(<MdMemory/>)

Upvotes: 3

Ricardo Sanchez
Ricardo Sanchez

Reputation: 5157

Got it! to achieve this you will need to

  1. Extract the path element like so MdMemory().props.children[0].props.d
  2. Create an svg string like const svg = "..."
const addDevice = () => {
  const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <path d="${MdMemory().props.children[0].props.d}"></path></svg>`;
  const svgGroup = Paper.project.importSVG(svg);
  svgGroup.fillColor = 'black';
  svgGroup.position = pointA.clone();
}

Upvotes: 2

Related Questions