Posted on , Updated on 

Step-by-Step Tutorial: How to transform SVGs into React Components in NextJS

Scalabe vector graphics (SVG) file is an XML-based vector image format for two-dimensional graphics. The key advantage of SVG images over other image formats like PNG or JPEG is that they can be scaled without losing quality. This makes SVGs ideal for a wide range of uses, like icons and loading animations in our development.

Here, we introduce how to convert an SVG into JSX code that can be rendered by React. To begin, we need to install a package called svgr, a versatile tool for transforming SVG files into React components.

$

After installing svgr, we need to add the following configuration to next.config.js, as described in the documentation:

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
module.exports = {
webpack(config) {
// Grab the existing rule that handles SVG imports
const fileLoaderRule = config.module.rules.find((rule) =>
rule.test?.test?.('.svg'),
)

config.module.rules.push(
// Reapply the existing rule, but only for svg imports ending in ?url
{
...fileLoaderRule,
test: /\.svg$/i,
resourceQuery: /url/, // *.svg?url
},
// Convert all other *.svg imports to React components
{
test: /\.svg$/i,
issuer: fileLoaderRule.issuer,
resourceQuery: { not: [...fileLoaderRule.resourceQuery.not, /url/] }, // exclude if *.svg?url
use: ['@svgr/webpack'],
},
)

// Modify the file loader rule to ignore *.svg, since we have it handled now.
fileLoaderRule.exclude = /\.svg$/i

return config
},

// ...other config
}

Next, create a new folder in your project specifically for storing the SVG files you need. I usually download SVGs from Flaticon.

1
2
3
4
5
6
ui
|-svgs
|-index.ts
|-Icon1.svg
|-Icon2.svg
|- ..

In this folder, we also created an index.ts file. This file is used to export multiple SVG icon files as React components, making it easy to import and use these icons in other parts of our application. Each export statement uses the default as syntax to assign a variable name (e.g., ChartPieIcon, SettingsIcon, etc.) to the default export of each SVG file. The content of this file looks like the following:

1
2
export {default as SearchIcon} from './Icon1.svg';
export {default as SettingsIcon} from './Icon2.svg';

With the above configuration, we can now import and use SVG images in our project just like regular React components. The React components generated by SVGR have the same attributes as the original SVG, such as fill, height, width, and so on, like this:

1
2
3
4
5
6
7
8
// import ...
import {SettingsIcon} from "@/app/ui/svgs";

export default function IconPage() {
return (
<SettingsIcon fill="#fff"></SettingsIcon>
)
}