Skip to content

Instantly share code, notes, and snippets.

@craftdelivery
Created October 16, 2019 22:24
Show Gist options
  • Save craftdelivery/011cd43014ea444378bab738be2b691c to your computer and use it in GitHub Desktop.
Save craftdelivery/011cd43014ea444378bab738be2b691c to your computer and use it in GitHub Desktop.
Image Component with fallback using hooks
import React, { useState } from 'react'
// assuming you have a custom fallback for a given param: id
const fallback = id => `https://fallback.distro.com/${id}.png`
const image = id => `https://images.distro.com/${id}.png`
export default props => {
const { click, id } = props
const [url, setUrl] = useState(image(id))
const err = () => setUrl(fallback(id))
return (
<img
alt=''
title={id}
src={url}
onError={err}
onClick={() => click(id)}
/>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment