DEV Community

Cover image for Next.js 14 Image Component: A Comprehensive Guide

Next.js 14 Image Component: A Comprehensive Guide

Wadi zaatour on February 20, 2024

Introduction When building modern web applications, optimizing image loading and performance is crucial. The Next.js Image component pro...
Collapse
 
vitya profile image
Victor Kasap

Thank you for the post!

src="/my-image.jpg" - exist
src="/my-image2.jpg" - doesn't exist

Please tell me how you will intercept an error if the image at the specific src does not exist.

Collapse
 
wadizaatour profile image
Wadi zaatour

Here you have to create a state to check the value of the src and apply a condition on it.

example:

import Image from 'next/image';
import { useState } from 'react';

const MyImage = () => {
  const [src, setSrc] = useState('/my-image.jpg');

  const handleError = () => {
    setSrc('/fallback-image.jpg'); // Set a fallback image if the original image fails to load
  };

  return (
    <Image
      src={src}
      alt="My Image"
      width={500}
      height={500}
      onError={handleError}
    />
  );
};

 export default MyImage;
Enter fullscreen mode Exit fullscreen mode
Collapse
 
wadizaatour profile image
Wadi zaatour • Edited

you can check my Article regarding useState() in React to deep dive more into the understanding of the concept! Good luck!

Collapse
 
respect17 profile image
Kudzai Murimi

Thanks for sharing!

Collapse
 
wadizaatour profile image
Wadi zaatour

You are welcome! Glad you find the article useful