DEV Community

Maaz Ahmed Khan
Maaz Ahmed Khan

Posted on

A Guide to Effortlessly Use SVGs in Next Js Projects

In the world of web development, Scalable Vector Graphics (SVGs) have become a staple for creating scalable, high-quality graphics that look great on any screen size. However, integrating SVGs into React projects can sometimes be a hassle.

SVGR is a command-line tool and webpack loader that transforms SVG files into React components. This means that instead of dealing with cumbersome SVG syntax directly in your code, you can simply import SVG files as React components and use them just like any other React component.

npm install @svgr/webpack --save-dev
Enter fullscreen mode Exit fullscreen mode

Next, configure SVGR in your Next.js project. You can do this by adding SVGR to your webpack configuration.

const nextConfig = {
  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;
  },
};

export default nextConfig;
Enter fullscreen mode Exit fullscreen mode

Now that SVGR is set up, you can start using it to import SVGs as React components directly into your Next.js project. Simply import the SVG file and use it like any other React component:

import MySvgIcon from '../path/to/MySvgIcon.svg';

const MyComponent = () => {
  return (
    <div>
      <MySvgIcon />
      {/* Other JSX */}
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

SVGR provides various options for customizing the generated React components. You can configure options such as dimensions, file naming, and component naming by passing options to SVGR through webpack configuration or directly in the import statement.

For more, checkout: https://react-svgr.com/docs/getting-started/

Happy coding!

Top comments (0)