Handling SVG images in NextJs

Installing webpack & Import as ReactComponent

Selman Koral
2 min readMay 3, 2023

In Next.js, the way you import SVG files as React components is slightly different from standard React applications. You can’t use the ReactComponent import as you would in Create React App or other setups. Instead, Next.js provides its own way to handle SVG imports.

To import SVG files as React components in Next.js, you can use the @svgr/webpack package, which is built into Next.js by default. Here's how you can do it:

1. Install @svgr/webpack (if not already installed): Check if you already have @svgr/webpack installed in your project's dependencies. If not, you can install it using npm

npm install @svgr/webpack --save-dev

2. Configure Next.js to Handle SVG Files:

In your Next.js project, you need to configure the webpack configuration to handle SVG files using SVGR. Create or edit the next.config.js file at the root of your project (if it doesn't exist) and add the following configuration:

// next.config.js
module.exports = {
webpack(config) {
config.module.rules.push({
test: /\.svg$/,
use: ['@svgr/webpack'],
});
    return config;
},
};

3. Import SVG Files in Your Components:

Now, you can import SVG files as React components in your components.

import Logo from '@/assets/logo.svg';
// Usage in JSX
<Logo />

How to fill your SGV on React ?

You have tried everything but still your svg doesn’t get the color?

I am not going to pass over the other common methods. They don’t work sometimes and this method will save your time.

  1. Don’t use fill and stroke attributes on SVG. Or it will cause overrides.
  2. Import the SVG as a component and set the fill and stroke props on the component as it is shown here:
import {ReactComponent as MyDamnSvg} from './logo_s.svg';

export default function App() {
return (
<div>
<MyDamnSvg fill="blue" stroke="red" />
</div>
);
}

You can delete unuseful attributes. Here is a svg example.

<svg width="400" height="400">
<path d=" M373.049561......."/>
</svg>

--

--