Skip to content
Advertisement

Best way to include reusable SVG in React

I am including SVG as reusable component on my react application. Sample of SVG component is as follows

import React from 'react';

export default function IconComponent(): JSX.Element {
    const svg = `
    <svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M36.4811 26.4927H29.7345C26.5728 26.4927 23.9995 23.921 23.9978 20.761C23.9978 17.5977 26.5711 15.0243 29.7345 15.0227H36.4811C37.1711 15.0227 37.7311 15.5827 37.7311 16.2727C37.7311 16.9627 37.1711 17.5227 36.4811 17.5227H29.7345C27.9495 17.5243 26.4978 18.976 26.4978 20.7593C26.4978 22.541 27.9511 23.9927 29.7345 23.9927H36.4811C37.1711 23.9927 37.7311 24.5527 37.7311 25.2427C37.7311 25.9327 37.1711 26.4927 36.4811 26.4927Z" fill="#0C1727"/>
</svg> `;

    return (
        <span
            className="icon icon-component"
            dangerouslySetInnerHTML={{ __html: svg }}
        />
    );
}


On page level, I am importing IconComponent and reusing it. Is there any other best way to include reusable SVGs in React pages which improves performance/page load?

Advertisement

Answer

1. SVG with webpack

command line

$ yarn add -D @svgr/webpack

webpack.config.js

const webpack = require('webpack');

module.exports = {
  entry: './src/index.js',
  module: {
    rules: [
      //...
      {
        test: /.svg$/,
        use: ['@svgr/webpack'],
      },
    ],
  },
  //...
};

then

import Star from 'star_icon.svg';

<Star />

2. SVG as component

import { ReactComponent as Star } from 'star_icon.svg';

<Star />
<Star width="64" height="64" fill="yellow" />

also you can use props like this.

3. SVG as path

import Star from 'star_icon.svg';

<img src={Star} />

I hope these codes will help you. Personally, I recommend the second method.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement