DEV Community

Zuhalcode
Zuhalcode

Posted on

Effective Ways to Integrate SVG into NextJS App

SVG (Scalable Vector Graphics) is a highly useful image format in web development due to its ability to maintain image quality across various sizes. However, integrating SVGs into a Next.js application is often considered complicated. This article provides a practical guide on how to effectively integrate SVGs into your Next.js project.

Building the Folder Structure

To integrate SVGs into your Next.js application, create an assets folder within src. Place your SVG files inside this folder.

src/
|── assets/
│   └── logo.svg
└── pages/
Enter fullscreen mode Exit fullscreen mode

Configuring Webpack for SVGs

To use SVGs as React components, you need to configure Webpack and install @svgr/webpack.

Install @svgr/webpack with the following command:

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

Open the next.config.js file in the root of your project.

Add the following configuration to integrate @svgr/webpack:

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

    return config;
  },
};
Enter fullscreen mode Exit fullscreen mode

Using SVGs in React Components

Import the SVG file that you placed in the src/assets folder:

import Logo from '@/src/assets/logo.svg';
Enter fullscreen mode Exit fullscreen mode

Use the SVG in your React component as follows:

import Logo from '../src/assets/logo.svg';

export default function HomePage() {
  return (
    <div>
      <h1>Selamat Datang di Website Kami!</h1>
      <Logo width={100} height={100} />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

By following these steps, you can easily integrate SVGs into your Next.js application, enhancing both the design and performance of your project. An organized folder structure and proper configuration will help you make the most of SVGs.

Top comments (0)