Created
October 16, 2019 22:24
-
-
Save craftdelivery/011cd43014ea444378bab738be2b691c to your computer and use it in GitHub Desktop.
Image Component with fallback using hooks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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