Share on LinkedInShare on PinterestShare on Youtube

Table of Contents

  • Summary
  • References

Summary

The Next.js Image component, `next/image` is an extension of the HTML `<img>` element. Evolved for the modern web, it has a wide range of useful features that improve the overall user experience of the app user. 


For example, there are built-in optimizations for improved performance. These features guarantee the served image is correctly sized for each device, using modern image formats. Also, its built-in image optimization feature does not affect the build time because the images are optimized on demand as the user requests them. Nextjs uses lazy loading by default.


This component has a required `src` prop that can be either a statically imported image file or path string. This props can be used for both local and remote images. 


In order to access a remote image, for every external url used in the src prop, there must be a hostname defined in the `next.config.js` file. Below is an example of how this is done. 


module.exports = {

images: {

domains: [‘www.hostname1.acme.com’,’www.hostname2.com’],

},

}


The `width` and `height` props are required, except for statically imported images, ot those with `layout=”fill”`.


Below is an example of how the Image component can be used.


import Image from ‘next/image’

const MyImage = (props) => {

return (

<Image src=”me.png” width={500} height={500} />

)

}

The Image object has a default loader that is used to generate URLs for your images. There are also additional built-in loader functions (i.e. ), and you may also define your own. Customization of the loader function can be done using the loader prop.


Below is an example of how to use the loader prop to define a custom loader function.

import Image from ‘next/image’

const myloader = ({ src, width, quality  }) => {

return `https://example.com/${src}?w=${width}&q=${quality || 75}`

}

const MyImage = (props) => {

return (

<Image loader={myLoader} 

src=”me.png” 

alt=”Picture of the author”

width={500}

height={500}/>

)

}

References

  • “next/image.” Next.js, https://nextjs.org/docs/api-reference/next/image. Accessed 20 July 2022.
  • “Basic Features: Image Optimization.” Next.js, https://nextjs.org/docs/basic-features/image-optimization. Accessed 22 July 2022.
  • Eagles, Lawrence. “Next.js automatic image optimization with next/image.” LogRocket Blog, 16 September 2021, https://blog.logrocket.com/next-js-automatic-image-optimization-next-image/. Accessed 27 July 2022.
Mensah Alkebu-Lan

About The Author

With 15+ years of experience in designing, developing, and maintaining JVM-based applications, ensuring seamless delivery of various IT projects, and successfully creating and executing software applications. Mensah also possesses strong expertise in leveraging Agile/Scrum methodologies, producing detailed technical documentation, and designing optimal software solutions.