Important Update
The Guide Feature will be discontinued after December 15th, 2023. Until then, you can continue to access and refer to the existing guides.
Author avatar

Solomon Ayoola

How to Load SVG with React and Webpack

Solomon Ayoola

  • Nov 20, 2019
  • 7 Min read
  • 166,315 Views
  • Nov 20, 2019
  • 7 Min read
  • 166,315 Views
Web Development
React

Introduction

As developers, we want all our images to look sharp and nice, even when we scale them up. To achieve the level of sharpness we want for our websites using bitmap images, such as JPEGs, GIFs, and PNGs, we have to increase file size, which greatly impacts the performance of the website. Vector images, however, looks crisp regardless of screen resolution and are relatively small in size.

In this guide, we'll learn about Scalable Vector Graphics (SVG) and explore the standard way of importing SVG in a React Application bundled with Webpack.

What is SVG?

SVG is an XML-based markup language for describing two-dimensional-based vector graphics. SVG is essentially to graphics what HTML is to text.

SVG images basically take the place of traditional images in other formats like JPEG, PNG, TIFF or GIF.

Advantages of using SVG over other image formats are:

  • SVG images can be searched, indexed, scripted, and compressed
  • SVG images are scalable
  • SVG can be created and edited with any text editor
  • SVG images do NOT lose quality even if they are resized or zoomed
  • SVG images can be animated, unlike other traditional image formats

Let's take a closer look at how to use SVG images. The xml code below creates a rectangle:

rectangle.svg

1<svg version="1.1"
2     baseProfile="full"
3     width="300" height="200"
4     xmlns="http://www.w3.org/2000/svg">
5  <rect width="100%" height="100%" fill="green" />
6</svg>
html

The most basic way to embed an SVG via an <img> element is to reference it in the src attribute, as you'd expect. You will need a height or a width attribute (or both if your SVG has no inherent aspect ratio).

1<img src="rectangle.svg" alt="A Rectangle Image with SVG" height="45px" width="45px" />
html

Usage with React

The easiest way of implementing an SVG in a React app is as follows:

1const App = () => <img src="/images/rectangle.svg" alt="A Rectangle Image with SVG" />;
javascript

However, in most cases, SVGs are usually pretty small, and in these cases we are better off inlining the images as data URLs, limiting the amount of requests a browser has to make to the server in order to render the webpage.

To transform an SVG image into a Data URL, we will need an appropriate webpack loader in our bundler. The most common webpack loader for this is svg-url-loader, which can be added as shown below:

1npm i svg-url-loader --save-dev
node

Add to webpack.config.js:

1const webpack = require('webpack');
2
3module.exports = {
4  entry: './src/index.js',
5  module: {
6    rules: [
7      {
8        test: /\.(js|jsx)$/,
9        exclude: /node_modules/,
10        use: ['babel-loader'],
11      },
12      {
13        test: /\.svg$/,
14        use: [
15          {
16            loader: 'svg-url-loader',
17            options: {
18              limit: 10000,
19            },
20          },
21        ],
22      },
23    ],
24  },
25  ...
26};
javascript

Import the file into your React app:

1import rectangle from 'images/rectangle.svg';
2
3const App = () => <img src={rectangle} alt="" />;
javascript

The output in the DOM will be something like this:

1<img src="ebbc8779488b4073081931bd519478e8.svg" alt="" />
html

You can check out svg-url-loader for more on the configurations.

In the examples above, the svg-url-loader can only be used in the traditional way, including images in a web application such as background-image or content. The next question is how to use an SVG image as a React Component.

SVG as a React Component

The solution is not farfetched. We'll need the help of another awesome webpack loader called svgr, which, according to the website, transforms the SVG into a ready-to-use React component.

So how do we use this awesome tool? Lets start by updating our webpack.config.js:

1const webpack = require('webpack');
2
3module.exports = {
4  entry: './src/index.js',
5  module: {
6    rules: [
7      {
8        test: /\.(js|jsx)$/,
9        exclude: /node_modules/,
10        use: ['babel-loader'],
11      },
12      {
13        test: /\.svg$/,
14        use: ['@svgr/webpack'],
15      },
16    ],
17  },
18  ...
19};
javascript

Then we can install it as a dev-dependency in the usual way:

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

Once you start your application, Webpack will do its thing and you don't need to worry about your SVGs anymore. You can put your SVG files anywhere in your src/ folder and import them wherever you need them as React components.

Lastly, import the file in your React app:

1import Image from 'path/image.svg';
2
3const App = () => (
4  <div>
5    <Image />
6  </div>
7)
javascript

This method is generally referred to as inline-svg.

A lightweight alternative solution to svgr is react-svg-loader.

1const webpack = require('webpack');
2
3module.exports = {
4  entry: './src/index.js',
5  module: {
6    rules: [
7      {
8        test: /\.(js|jsx)$/,
9        exclude: /node_modules/,
10        use: ['babel-loader'],
11      },
12      {
13        loader: 'react-svg-loader',
14        options: {
15          jsx: true // true outputs JSX tags
16        }
17      }
18    ],
19  },
20  ...
21};
javascript

And install as usual:

1npm install react-svg-loader --save-dev
node

For the most part, we do not want all our SVG files to be loaded as a React components. We could combine the above methods depending on the use case. All we have to do is update our webpack configuration.

The example below uses svgr and url-loader, a webpack loader which transforms files into base64 URIs.

1const webpack = require('webpack');
2
3module.exports = {
4  entry: './src/index.js',
5  module: {
6    rules: [
7      {
8        test: /\.(js|jsx)$/,
9        exclude: /node_modules/,
10        use: ['babel-loader'],
11      },
12      {
13        test: /\.svg$/,
14        use: ['@svgr/webpack', 'url-loader'],
15      },
16    ],
17  },
18  ...
19};
javascript

The usage in your application would look this:

1import imageUrl { ReactComponent as Image } from 'path/image.svg';
2
3const App = () => (
4  <div>
5    <img src={imageUrl} alt="" />
6    <Image />
7  </div>
8)
javascript

Conclusion

This guide has provided you with a quick intro into how to import SVG into your React Application using webpack as the bundler.

Here are a few other resources on SVG and its numerous applications: