Show placeholder image in ReactJS
Imagine if you are displaying an image from the server in your React app. And the image gets deleted from the server. You do not want to show the broken image icon, as it does not look professional. You can show a placeholder image in your ReactJS App if the original image fails to load.
The following code will by default show the “Jackie Chan 2.jpg” image. If that image fails to load, it will render the “default-img.jpg” image inside the “img” folder.
Be careful: If the placeholder image does not exist as well, it will stuck in an infinite loop. To solve this problem, DO NOT save the placeholder image on the server. Always keep the placeholder images on the client side.
function MyApp() {
const { useState } = React
const [image, setImage] = useState("img/Jackie Chan 2.jpg")
return (
<>
<h1>Hello React JS</h1>
<img src={ image }
style={{
width: "100%"
}}
onError={function () {
event.target.src = "img/default-img.jpg"
}} />
</>
)
}
ReactDOM.createRoot(
document.getElementById("app")
).render(<MyApp />)
As an example, you can use this image as a placeholder. Make sure to download it in your “img” directory. That’s how you can show a placeholder image in ReactJS if the original image fails to load. You can also read more articles on ReactJS.