DEV Community

Cover image for Next.js Image Component Cheatsheet
iskurbanov
iskurbanov

Posted on

Next.js Image Component Cheatsheet

Cheatsheet for Next.js Image Component with common use cases

After the introduction of the Image component in Next.js version 10, it is rare to use Next.js with the regular <img /> component and is now even considered incorrect! This Article is to help you learn and remember the most common uses cases for the Next.js Image component.

Quick Cheatsheet:

1. with predefined width and height:

import Image from 'next/image'
import example from '../asset/myimage.png'

const Example = () => {
  return (
    <Image
      src={example}
      alt="Alt text for the picture"
      width="350px"
      height="300px"
    />
)

Enter fullscreen mode Exit fullscreen mode

2. with predefined width and height with layout prop:

With the layout prop, you get 5 options:

'fill'
'responsive'
'intrinsic'
'fixed'
and now 'raw'

import Image from 'next/image'
import example from '../asset/myimage.png'

const Example = () => {
  return (
    <Image
      src={example}
      alt="Alt text for the picture"
      width="350px"
      height="300px"
      layout="responsive" 
  />
)
Enter fullscreen mode Exit fullscreen mode

with layout fill (dynamic image size)

import Image from 'next/image'
import example from '../asset/myimage.png'

const Example = () => {
  return (
    <Image
        src={example}
        alt="Alt text for the picture"
        layout="fill"
        objectFit="cover"
        quality={100}
   />
)
Enter fullscreen mode Exit fullscreen mode

3. styling using Tailwind CSS

import Image from 'next/image'
import example from '../asset/myimage.png'

const Example = () => {
  return (
    <div className="relative w-24 h-24 border border-gray-200 rounded-md overflow-hidden">
        <Image
           src={product.image}
           alt={product.title}
           layout="fill"
           objectFit="cover"
       />
    </div>
)
Enter fullscreen mode Exit fullscreen mode

4. Next.js Image as a background image

import Image from 'next/image'
import example from '../asset/myimage.png'

const Background = () => (
  <div>
    <ViewSource pathname="pages/background.js" />
    <div className="fixed h-screen w-screen overflow-hidden
  -z-10">
      <Image
        alt="Mountains"
        src="/mountains.jpg"
        layout="fill"
        objectFit="cover"
        quality={100}
      />
    </div>
  </div>
)

Enter fullscreen mode Exit fullscreen mode

In the comments below, suggest some of your own favorite/most common use cases!

Learn more about Next.js at BuildNextShop.com

Top comments (0)