Skip to content Skip to sidebar Skip to footer

React : Returning Svg Contents As Variable?

I am currently doing this: class Checked extends React.Component { render() { return (

Solution 1:

Option 1: Wrap with a stateless component:

constImgTable = () => (
  <svgwidth="24"fill="#00ea00"height="24"viewBox="0 0 24 24"><pathd="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/></svg>
);

exportdefaultImgTable;

Now you can import it as a component:

importImgTablefrom'../img/ImgTable'classCheckedextendsReact.Component {
  render() {
      return<ImgTable />;
  }
}

Option 2: Use dangerouslySetInnerHTML (notice the name). However, you'll need to convert the SVG to string on import using something like babel-plugin-transform-svg-import-to-string:

import imgTable from'../img/catering_table.svg'// this will return a stringclassCheckedextendsReact.Component {
  render() {
      return<divdangerouslySetInnerHTML={{__html:imgTable }} />;
  }
}

Solution 2:

babel-plugin-inline-react-svg is a plugin that allows you do exactly what you hinted at in your question. It simply creates a react component for every node in the svg file. Then it wraps the the entire component tree with a root element that you can easily name.

Import you svg like this import SampleSVG from './sample.svg';. And render it in your application like this <SampleSVG />. It's safe and simple.

Solution 3:

You can pass an SVG to a variable in React as follows:

const checkIcon = {
    icon: <svgdata-name="Group 1642"width="25.771"height="25.771"className="info--text-icon"viewBox="0 0 25.771 25.771"><pathdata-name="Path 99"d="M11.979 17.51h-.021a.97.97 0 01-.694-.313l-4.889-5.309a.971.971 0 011.429-1.316l4.2 4.566L23.661 3.521a.971.971 0 111.371 1.375L12.665 17.231a.972.972 0 01-.686.279z"fill="#44bbc7" ></path><pathdata-name="Path 100"d="M12.885 25.771a12.885 12.885 0 010-25.771.971.971 0 010 1.943 10.943 10.943 0 1010.943 10.942.971.971 0 011.943 0 12.9 12.9 0 01-12.886 12.886z"fill="#44bbc7" ></path></svg>
  };

And to call the variable:

constInformations = () => {
  return (
      <>
       {check.icon} This is SVG with React
      </>
  )
}

Post a Comment for "React : Returning Svg Contents As Variable?"