Welcome to NextJS Guru!

  • How to use SVG files as regular images in Next.js

    You can easily use optimized SVG images in your Next.js project without the need of manual importing of the SVG files as components with @svgr/webpack loader module.

    The old way of importing svg files into a Next.js project was to configure webpack loader to handle .svg extension files and import them as components, this way, however gives you less control over images’s size because you need to manually modify the file source to adjust its displayed sizes.

    This method can be cumbersome and if you want more control over imported svg’s you can use the Image component from next/image to directly display svgs as if they were regular png or jpeg files.

    Simply save the svg file in the public directory and import it using the Image component like this:

    import Image from 'next/image'
    import Link from 'next/link'
    
    export default function Logo() {
      return (
        <div>
          <Link href={'/'}>
            <Image
              src={'/logo.svg'}
              width={100}
              height={10}
              alt="The logo alt text"
            />
          </Link>
        </div>
      )
    }
    

    This way of importing svgs gives you the convenience of setting the svg sizes as easy as regular image files.