In Next.js, there are several approaches to importing and using SVG files. Here are some common methods:
1. Using the <img> Tag
This is the simplest method: directly import the SVG as an image source:
jsximport React from 'react'; const MyComponent = () => ( <div> <img src="/path/to/your-image.svg" alt="My SVG Image" /> </div> ); export default MyComponent;
In this example, place the SVG file in the public folder (typically the public directory), and reference it as you would with a regular image.
2. Using Next.js's Image Component
Next.js provides a built-in Image component for optimized image loading:
jsximport Image from 'next/image'; import React from 'react'; const MyComponent = () => ( <div> <Image src="/path/to/your-image.svg" alt="My SVG Image" width={500} height={500} /> </div> ); export default MyComponent;
Similar to the <img> tag method, place the SVG image in the public directory.
3. Using SVG as a Component
Starting with Next.js 9.5.4, configure the inline-react-svg plugin in the next.config.js file to directly import SVG files as React components:
First, install the required plugin:
bashnpm install react-svg-loader --save-dev
Then configure it in next.config.js:
jsconst withReactSvg = require('next-react-svg'); const path = require('path'); module.exports = withReactSvg({ include: path.resolve(__dirname, 'path/to/svgs'), webpack(config, options) { return config; } });
After that, directly import the SVG file and use it as a component:
jsximport React from 'react'; import YourSvg from '/path/to/your-image.svg'; const MyComponent = () => ( <div> <YourSvg /> </div> ); export default MyComponent;
This makes handling SVGs as straightforward as working with React components, allowing you to easily add className or other attributes.
4. Using next-svg
next-svg is a Next.js plugin that enables importing SVG files directly as React components in your project. The usage mirrors next-react-svg: first install the plugin, then configure it in next.config.js.
These are several approaches to importing SVG files in Next.js. Select the method that best fits your project requirements and preferences.