How to use svgs in nextjs ?

How to use svgs in nextjs ?

ยท

2 min read

Table of contents

I use nextjs a lot whenever I build something. In Nextjs you can't directly use svgs and use it according to your convenience. When I was building one project where I had to import svg and show it in component, Nextjs was not able to show it in the web browser.

The two best solutions which are available online and can help import svgs properly are listed below. You can use any method listed below to import svgs properly and use in Nextjs

Solution 1

Use SVGR. Install it by running the below command

npm i @svgr/webpack

Add the following code in next.config.js file and you are all done

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

    return config;
  }
};

Restart the nextjs server, as next.config.js file is created / updated.

After that, you can use svgs without any issues. Below is one simple example to import svg and use in your code

import React from 'react';
import SVGBackground from "./Background.svg";

export const AppComponent = () => (
  <div>
    <SVGBackground />
  </div>
);

Solution 2

Use babel-plugin-react-svg. Install it first

npm install --save-dev babel-plugin-inline-react-svg

Create / Update .babelrc file in the root of your project with the below code

{
  "presets": ["next/babel"],
  "plugins": ["inline-react-svg"]
}

And you are done. You can now use svg as components in Nextjs properly without any hassle.

These two are my favourite methods to use svgs in Nextjs. There are other available methods also which can be found in the internet which you can also use.

Thanks for reading this article. I hope it was useful.

Keep learning and keep rocking ๐Ÿš€

ย