I
I
Igor Vasiliev2021-08-17 13:54:52
Images
Igor Vasiliev, 2021-08-17 13:54:52

Next JS how to catch an error if the image returns a 404 error?

Hello.

Imagine the situation, you have a website that receives data from the database, the database contains information about pictures in the form of links, but it so happened that the manager manually deleted the pictures from the folder and grabbed the excess. Link - yes, pictures - no. That is, not undefined is returned, but a link, Next JS swears at this, the console is red due to 404 errors.

Question:
How to catch this kind of error <img src="?" />
if the path to the image returns a 404 error, show the image by default. On normal html, it will be just an alt icon, indicating that there is an image there. Next JS is JSX, and sometimes such errors break pages, especially if data is taken from outside, via API or through requests.

Who faced this, how to fix it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Egor Zhivagin, 2021-08-17
@Isolution666

You can put an onError listener on the img, it fires in case of any error while loading. You will need to look at the error object, somehow understand from it that this is exactly 404 and pass a link to the default image to the src of the same image

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question