A picture of a file, a React logo, and a CopyCat logo.

React SVG: How to use SVGs best in React

April 1, 2022
Uncle Big Bay
React Best Practices

The Fastest Way to Build React UI

Convert Figma designs to production-ready React.js code. Build stunning apps and landing pages faster than your peers and competitors.

In this article, we’ll look at the SVG image format, how to import SaVG in react, how to convert SVG to react components and the benefits and drawbacks of using SVGs in react.

What is an SVG?

SVG is a W3C recommendation that stands for Scalable Vector Graphics. It’s a text-based image format with high scalability and efficiency, it can be used to define vector-based graphics in XML (Extensible Markup Language), giving them a quality edge over other image formats like png, jpeg, and gif.
The file extension of an SVG image is .svg and they do not lose quality when zoomed or resized, making them more efficient than other image formats over a wide range of screen sizes.

How to use SVG?

SVGs are scalable, fully customizable, lightweight, and easy to animate image formats. You can use SVGs as an icon, logo, image, or backdrop image in your react application.

Top 5 Places to get React SVGs?

You can use React SVG in a variety of ways in your react application; here’s a list of places where you can get free React SVG icons and images:

  1. Heroicons

Heroicons is an extension of Tailwind CSS. It provides high-quality SVG icons for react. You can copy the SVG tags or the ready-made react SVG tags into your JSX component directly from their website.

heroicons
  1. Bootstrap Icons

Bootstrap provides a large collection of SVG icons but unlike Heroicon, you can only get the SVG tag without the JSX format.

rewact svg bootstrap icons
  1. Undraw

Undraw offers a very large collection of image illustrations in SVG formats, you can change the colors of the SVG image directly from Unsplash before you download them.

undraw react svg
  1. Tabler Icons

Tabler icons is an open-source platform that provides customizable SVG directly from their website. They offer over 1000+ SVG icons for free.

tabler icons
  1. Feather Icons

Feather is a collection of simply beautiful open source SVG icons. Each icon is on a 24×24 grid with an emphasis on simplicity and consistency.

react svg feather icons

How to Import SVG React?

You must first learn how to import SVG in react applications before you can utilize them. Here are a couple of options for how to import svg file in React:

  • Importing SVG in react as an image tag
  • Import SVG in react as JSX
  • Importing SVG as react component (Inline SVGs)

Importing SVGs in React Image Tag

The easiest way to make use of react SVG logo is by importing them in the img src attribute like this:

1
2
3
4
5
6
7
8
9
import myLogo from '/path/to/image.svg'
 
const Button = () => {
  return (
    <button>
      <img src={myLogo} alt="SVG logo image"/>
    </button>
  );
}

Though this approach appears to be simple, the only drawback is that, unlike the other import options, you cannot customize the SVG imported in the image element using CSS. After importing your SVG, there are several ways how to use svg icon in react.

How to use SVG as a Background Image?

The SVG image format can be used as a background image in the same way as the PNG, JPEG, and GIF image format.

1
2
3
.container {
  background-image: url(/path/to/image.svg);
}

Importing SVG in React as JSX

Another way to import SVG in react with full control of its customization is by converting the regular SVG tags to react SVG in JSX. This approach is possible because SVGs are written in XML format (like HTML) which can be converted into react JSX.
This is an example of a regular SVG tag:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<svg
  class="h-6 w-6"
  fill="none"
  viewBox="0 0 24 24"
  stroke="currentColor"
  stroke-width="2"
>
  <path
  stroke-linecap="round"
  stroke-linejoin="round"
  d="M11 19l-7-7 7-7m8 14l-7-7 7-7"
  />
</svg>

This is an example of a regular SVG that has been converted to react S:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<svg
  className="h-6 w-6"
  fill="none"
  viewBox="0 0 24 24"
  stroke="currentColor"
  strokeWidth={2}
>
  <path
  strokeLinecap="round"
  strokeLinejoin="round"
  d="M11 19l-7-7 7-7m8 14l-7-7 7-7"
/>
</svg>

The two SVG tags above will give the same result as follow:

svg tags

Importing SVGs as React Component

Converting SVG into a react component is another approach to using SVG in react. This technique is supported by default by Create-react-app and Gatsby, but if you’re using webpack or Percel, you’ll need to add some extra settings to your webpack or percel configuration (read on for the configuration).

How to convert SVG into React Components

React components are reusable code chunks wrapped in a class or function component. In this example, we’d want to transform our SVG to a react reusable function component, which would decrease the number of times we have to manually import tags. 
More information on constructing react.js components can be found here.

Converting SVG into a React Component

The easiest way to convert an SVG to react component is by creating a functional or class component that returns the react SVG like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
export const LeftArrow = () =>{
  return(
    <svg
    className="h-6 w-6"
    fill="none"
    viewBox="0 0 24 24"
    stroke="currentColor"
    strokeWidth={2}
  >
    <path
    strokeLinecap="round"
    strokeLinejoin="round"
    d="M11 19l-7-7 7-7m8 14l-7-7 7-7"
  />
  </svg>
  )
}

This approach is only possible if you use create-react-app, since create-react-app includes SVGR to your app setup under the hood, which allows react to import SVG as a component.
Now, you can import and render the react SVG component in another component like this:

1
2
3
4
5
6
7
8
9
import { LeftArrow } from './path/to/LeftArrow.jsx'
 
export const Button = () =>{
  return(
    <button>
      <LeftArrow />
    </button>
  )
}

Converting SVG into a React Components with SVGR

If you didn’t use create-react-app to make your react app, you’ll have to manually set up SVGR. SVGR takes a raw SVG and transforms it into a React SVG component that’s ready to use. More information on the SVGR library can be found here.
Install SVGR by running the code below:

1
npm install --save-dev @svgr/webpack

or use yarn:

1
yarn add --dev @svgr/webpack

Next, update your webpack.config.js file with the following code:

1
2
3
4
5
6
7
8
9
10
11
module.exports = {
  module: {
    rules: [
      {
        test: /\.svg$/i,
        issuer: /\.[jt]sx?$/,
        use: ['@svgr/webpack'],
      },
    ],
  },
}

Finally, we can import SVG as a react component and reuse them across other components like this:

1
2
3
4
5
6
7
8
9
import { LeftArrow } from './path/to/LeftArrow.jsx'
 
export const Button = () =>{
  return(
    <button>
      <LeftArrow />
    </button>
  )
}

How to use SVGR as data-url

You’ll need to build up a react SVG loader to be able to utilize SVG as a URL in your image tag. This will allow us to use SVGs as an inline element as well. We show you how to load svg in react.
Install react SVG loader into your bundler with the command below:

1
npm install svg-url-loader --save-dev

Next, update your webpack config file with the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const webpack = require('webpack');
 
module.exports = {
  entry: './src/index.js',
  module: {
    rules: [
      {
        test: /\.svg$/,
        use: [
          {
            loader: 'svg-url-loader',
            options: {
              limit: 10240,
              // make all svg images to work in IE
              iesafe: true,
            },
          },
        ],
      },
    ],
  },
};

With the loader configuration above, we can now use our SVG image as a data-url in our react application like this:

1
2
3
4
5
6
7
8
9
import myLogo from '/path/to/image.svg'
 
const Button = () => {
  return (
    <button>
      <img src={myLogo} alt="SVG logo image"/>
    </button>
  );
}

In the DOM, the SVG image will be compiled into a URL like this:

1
<img src="wes49idjdur935jujd8907jdh.svg" alt="SVG logo image" />

How to Conditionally Render SVG in React?

We can do more with React SVGs by rendering them based on the conditions of our react app component. We’ll use a hamburger open and close SVG icons as an example in the tutorial.
Create a new Hamburger.jsx file in your react application and paste the code below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
export const Hamburger = () =>{
  const [ isOpen, setisOpen ] = React.useState(false)
  return(
    <React.Fragment>
    { isOpen ? (
      <button
        onClick={()=>setisOpen(false)}
       >
        <svg
           xmlns="http://www.w3.org/2000/svg"
           fill="none"
           viewBox="0 0 24 24"
           stroke="currentColor"
           strokeWidth={2}
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            d="M6 18L18 6M6 6l12 12"
           />
        </svg>
      </button>
    ):( <button
          onClick={()=>setisOpen(true)}
         >
          <svg
            xmlns="http://www.w3.org/2000/svg"
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
            strokeWidth={2}
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              d="M4 6h16M4 12h16M4 18h16"
            />
          </svg>
         </button>
        )
      }
    </React.Fragment>
  )
}

When the isOpen state of the hamburger component is false, we want to display the open SVG icon, and when the isOpen state of the component is true, we want to render the close SVG icon.
Add the following CSS line of code:

1
2
3
4
svg{
  height: 40px;
  width: 40px;
}

Now, we can render our SVG icons based on the state of our Hamburger component:

User-uploaded image: ezgif-4-020c7392c3.gif

You can learn more about react conditional rendering from here.

How to Animate SVGs?

In addition to being scalable and maintaining high resolutions across multiple screen sizes, SVG supports the animation of its components with CSS. Let’s have a look at how we can animate our SVG image. 
Our finished SVG animation output will look somewhat like this: 

User-uploaded image: ezgif-4-0a988639f4.gif

First, add an SVG inline to your component like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
export const ArrowSVG = () =>{
  return(
      <svg
        xmlns="http://www.w3.org/2000/svg"
        className="h-6 w-6"
        fill="none"
        viewBox="0 0 24 24"
        stroke="currentColor"
        strokeWidth={2}
      >
        <path
          strokeLinecap="round"
          strokeLinejoin="round"
          d="M11 19l-7-7 7-7m8 14l-7-7 7-7"
        />
      </svg>
  )
}

Advantages of Using SVG Images

Next, we’ll define the animation we want using the CSS @keyframes property. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
svg {
   height: 50px; 
   animation: rotate 6s linear infinite;
}
 
@keyframes rotate{
   0% {
      transform:rotateY(0deg);
   }
    
   50% {
      transform:rotateY(180deg);
   }
    
   51% {
      transform:rotateY(180deg);
   }
    
   99% {
      transform:rotateY(0deg);
   }
    
   100% {
      transform:rotateY(0deg);
   }
}

We want the SVG to rotate from 0 degrees at 0% to 180 degrees at 50%, 180 degrees at 51%, and back to 0 degrees at 99 percent to 100 percent using the CSS code above.

What makes SVG better than other image formats? Some of the benefits of SVG images over other image formats are listed below:

  1. SVGs are Editable:

SVGs are text-based and composed entirely of XML formats; they can be easily created, animated, and altered in any text editor.

  1. SVGs are Scalable:

Images created using SVG may be scaled to any size without losing quality. Because their quality is independent of resolution, they offer the highest visual quality over a wide range of screen sizes.

  1. SVGs are Good for Accessibility and SEO: 

Because SVG files are made up of text, they can be read by a screen-reader and can be searched, indexed, and scripted to boost a website’s SEO.

  1. SVGs are Customisable:

SVGs are made up of XML and can be accessed through the DOM in the same way that conventional HTML can. CSS can be used to style SVG attributes including color, height, width, and background color.

  1. SVGs have Small File Size

The attributes of an SVG file, such as masking, color, effect, and layers, determine the size of the file. Pixels determine the file size of other image formats such as png, jpeg, and gif.

  1. SVGs are flexible.

You can use SVGs in a variety of ways, including displaying react logos and icons. Additionally, you can also create Graphs, animations, and CSS effects using SVG.

  1. SVGs can be animated.

You can use Web Animation APIs, WebGL, CSS animations, and other techniques to animate SVG.

  1. SVGs are printable.

Disadvantages of using SVGs

  1. SVGs are not Support by Legacy Web Browsers:

Internet Explorer and other legacy browsers do not support SVGs. You must avoid SVGs if your project needs to work on legacy browsers.

  1. SVGs can only Support Less Details:

SVGs are good for logos and icons, but they aren’t good for high-density colors since they can’t display as much detail as pixel-based formats like PNG and JPEG.

  1. Google do not index SVGs are not indexed as they are text-based.

Wrapping Up

Most recent browsers support SVGs which are enhanced image formats. Because of their text-based nature, they are scalable, lightweight, and ideal for accessibility or SEO. You may also use any text editor to edit SVG files and customize them using CSS.
Although understanding how to use SVG in React might be challenging, we hope that this post has clarified how to use them and the benefits they provide.

Where do you go next?

Now that you know how to use SVGs in your React application, check out the video resources below to learn more:

  1. Learn more about SVG Components in React:
  1. Check out A beginners guide to SVG | Part One: The Why, What, and How:

Also check out CopyCat for converting your Figma designs to React with the click of a button. You’ll reduce your time spent developing, eliminate sprint delays, and build faster than your competition.

Interesting Reads From Our Blogs

Related Articles

  • React.js

    Ultimate Guide to Fetching Data from API using React Fetch with Clear…

    Introduction to Fetching Data from API Often times, in fullstack web applications, you are required to either interact with a database; this can be a relational or non-relational database, or interact with an API. In such scenarios, you will need to…

    July 20, 2022
  • React.js

    How to Build Tabs in React with Material UI Tabs

    Introduction Tabs are elements that help you navigate between multiple elements when only one can be viewed at a time. In this article, we'll look at the Material UI tabs component, how they work, and how to create tab components…

    December 24, 2022

Convert Figma To React

Convert Figma designs to production-ready React.js code. Build stunning apps and landing pages faster than your peers and competitors.

Convert Design to Code