How to check for broken images in React with JavaScript?

Sometimes, we want to check for broken images in React with JavaScript

In this article, we’ll look at how to check for broken images in React with JavaScript.

How to check for broken images in React with JavaScript?

To check for broken images in React with JavaScript, we can set the onError of the img element to a error handler function.

For instance, we write:

import React from "react";

export default function App() {
  const onError = (e) => {
    console.log(e);
  };

  return (
    <>
      <img onError={onError} src="abc" alt="abc" />
    </>
  );
}

to set the onError of the img element to the onError function.

Since the src prop is set to an invalid URL, we see the error object logged in onError.

Conclusion

To check for broken images in React with JavaScript, we can set the onError of the img element to a error handler function.