1

I need to render .svg files. I do not want to use dangerouslySetInnerHTML. I am able to successfully render an svg if I copy the svg contents directly and render it from a component.

However, this is not very reusable. I don't want to copy the contents from each .svg file. I would like to be able to import an svg file and pass that into my component that will then render the contents.

Here's what I have done so far, but it is not rendering my svg.

I have created a component that accepts an imported svg file, like this:

import React from "react";

class SvgComponent extends React.Component {
  constructor(props) {
     super(props);
   }
  render() {  
    return (
     props.svg // this works if I copy my .svg contents here (<svg>....</svg>)
  );
 }
};

SvgComponent.propTypes = {
  svg: React.PropTypes.string.isRequired,
};

export default SvgComponent;

And here is how I am using that component:

import mySvg from './images/mySvg.svg';
const Icon = (props) => { 
  return (
    <svgComponent svg={mySvg} />
  );
};

Icon.propTypes = {
  icon: React.PropTypes.string.isRequired,
};

export default Icon;

This does not work -- it does not show my svg on the webpage, or even in the dom. When I inspect the page, all I see is an empty svgComponent:

<svgComponent />

Any help on getting .svg files to display in react would great!

JAck28
  • 899
  • 4
  • 15
  • 40
  • Possible duplicate of [How do I load SVGs directly in my React component using webpack?](https://stackoverflow.com/questions/30844298/how-do-i-load-svgs-directly-in-my-react-component-using-webpack) – jeffesp Jun 19 '17 at 20:25
  • This is not a duplicate. I do not want to use dangerouslySetInnerHTML. – JAck28 Jun 20 '17 at 14:58
  • Fair enough. I missed that part of the question. – jeffesp Jun 21 '17 at 18:40

1 Answers1

3

I created a module to solve this problem. With it you can load the svg and manipulate its elements using JSX without having to paste the svg code.

Npm package:https://www.npmjs.com/package/react-samy-svg

Check an example on Glitch: https://fossil-transport.glitch.me

It's simple to use

<Samy path="path to your svg file">
     <Proxy select="#Star" fill="red"/>
 </Samy>

Whenever you need to change some SVG attribute just create a Proxy element and use the 'select' prop (accepts CSS selectors). All props set on Proxy will be forwared as attributes to the SVG element(s)

Hugo Zapata
  • 4,314
  • 5
  • 29
  • 32