Hide an image if src is null or undefined in React

HTML allows to use the onerror event on images to hide them when the src URL returns a 404, or when it's undefined or null.

Example:

html
<img src = null onerror = 'hide(event)'/>

<script>
function hide(event){
    
  event.target.style.display = 'none'
  
}
</script>

In React, you can use the onError event to prevent 404 errors.

Example:

jsx
import React from 'react'

const Picture = () => {

    return <img src = 'https://error404.jpg' onError = {e => e.target.style.display = 'none'}/>

}

export default Picture

But if the src is null or undefined, the onError event is not triggered. In that case, you can hide the "Image not found" element by choosing a Base64 transparent picture.

Example:

jsx
import React from 'react'

const Picture = () => {

    // Let's assume that getImageURL gets a URL of a picture or it returns null/undefined if it couldn't find one
    const url = getImageURL()

    // This approach prevents 404 errors, null or undefined URLs to display the "Image not found" icon
    return <img src = {url || 'data:image/gif;base64,R0lGODlhAQABAAAAACwAAAAAAQABAAA='} onError = {e => e.target.style.display = 'none'}/>

}

export default Picture

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.