LabHub

Blog

Images in Next.js

한국어English日本語

Introduction

The tailwind starter blog has out of the box support for Next.js's built-in image component and automatically swaps out default image tags in markdown or mdx documents to use the Image component provided.

Usage

To use in a new page route / javascript file, simply import the image component and call it e.g.

import Image from 'next/image'

function Home() {
  return (
    <>
      <h1>My Homepage</h1>
      <Image src="/me.png" alt="Picture of the author" width={500} height={500} />
      <p>Welcome to my homepage!</p>
    </>
  )
}

export default Home

For a markdown file, the default image tag can be used and the default img tag gets replaced by the Image component in the build process.

Assuming we have a file called ocean.jpg in data/img/ocean.jpg, the following line of code would generate the optimized image.

![ocean](/static/images/ocean.jpg)

Alternatively, since we are using mdx, we can just use the image component directly! Note, that you would have to provide a fixed width and height. The img tag method parses the dimension automatically.

<Image alt="ocean" src="/static/images/ocean.jpg" width={256} height={128} />

Note: If you try to save the image, it is in webp format, if your browser supports it!

ocean

Photo by YUCAR FotoGrafik on Unsplash

Benefits

Limitations

Comments

No comments yet.

Sign in to leave a comment