Categories
JavaScript Answers

How to reference an image in Next.js?

Spread the love

In Next.js, you can reference an image by importing it into your JavaScript or TypeScript code using the import statement or by using the Image component provided by Next.js.

1. Importing Images

You can import images directly into your JavaScript or TypeScript files using the import statement:

import Image from 'next/image';
import myImage from '../public/my-image.jpg'; // Path to your image file

function MyComponent() {
    return (
        <div>
            <img src={myImage} alt="My Image" />
        </div>
    );
}

export default MyComponent;

2. Using the Image Component

Next.js provides an Image component that optimizes images for performance:

import Image from 'next/image';
import myImage from '../public/my-image.jpg'; // Path to your image file

function MyComponent() {
    return (
        <div>
            <Image src={myImage} alt="My Image" width={500} height={300} />
        </div>
    );
}

export default MyComponent;

Static Assets:

Place your images in the public directory at the root of your Next.js project.

Next.js automatically serves files from the public directory at the root URL.

For example, if you have an image named my-image.jpg in the public directory, you can reference it as /my-image.jpg.

Make sure to adjust the path accordingly when importing the image into your components.

Using Next.js’s built-in image optimization features provides better performance and automatic optimization of images based on the device’s screen size and resolution.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *