Configure React to Import SVGs as React Components.

Arbaz Ajaz
2 min readMar 25, 2021

--

Importing SVG Into the Code.

If importing your SVG into the code and rendering it gives you the following error:

Scary error that pops up.

This means you don’t have the loader to import SVGs as React component.

Well, to get it to work, we’ll use @svgr/webpack

It is a loader to load SVG files, so we’ll need to tweak the webpack configurations, you can checkout the package’s homepage for more information or follow along.

Install it as a dev dependency using yarn add --dev @svgr/webpack

Now, that we have that installed, I’ll be using react-app-rewired to override any configurations (append my configurations) that already exist. Install it as a dev dependency too using yarn add --dev react-app-rewired

Now we’ll replace react-script with react-app-rewired for our scripts in /package.json . It will look like this:

Replacing react-scripts with react-app-rewired

The last part is overriding the configurations (appending my configurations), for react-app-rewired to work, it needs a file named *drum roll please* /config-overrides.js file. Create a new file named config-overrides.js right next to the cute /package.json file.

Folder structure is:

Example Project Structure.

Open it up with your favorite editor, and add the following bit of code.

module.exports = (config) => {
config.module.rules[1].oneOf.splice(0, 0, {
test: /\.svg$/,
use: ["@svgr/webpack"],
})
return config
}

Bit chunk of code, I know. Hold on, let me explain what is going on.

We get the webpack configuration as a parameter to this function, and we add a new rule, that checks if the file ends with .svg and if it does, we use the @svgr/loader

Now, all you have to do is launch the application using yarn start and witness the magic.

--

--

Arbaz Ajaz

Arbaz is a MERN Stack developer, aiming to make learning programming accessible and straight forward