Last active
June 26, 2020 12:31
-
-
Save hrdtbs/a0fc073dca3890421bd34b280936268f to your computer and use it in GitHub Desktop.
This file contains 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
/** @jsx jsx */ | |
import { css, jsx, keyframes } from "@emotion/core" | |
import React, { useCallback, useEffect, useRef, useState } from "react" | |
export const skeletonKeyframes = keyframes` | |
0% { | |
background-position: -200px 0; | |
} | |
100% { | |
background-position: calc(200px + 100%) 0; | |
} | |
` | |
export const SkeltonImage: React.FC<React.ImgHTMLAttributes<HTMLImageElement>> = ({ ...props }) => { | |
const [loaded, setLoaded] = useState(false) | |
const ref = useRef<HTMLImageElement>(null) | |
const handleLoaded = useCallback(() => { | |
setLoaded(true) | |
}, []) | |
useEffect(() => { | |
if (ref.current?.complete) { | |
setLoaded(true) | |
} | |
}, []) | |
return ( | |
<img | |
ref={ref} | |
onLoad={handleLoaded} | |
aria-busy={!loaded} | |
css={css` | |
&[aria-busy="true"] { | |
cursor: wait; | |
background-color: #eee; | |
background-image: linear-gradient(90deg, #eee, #f5f5f5, #eee); | |
background-repeat: no-repeat; | |
background-size: 200px 100%; | |
animation: ${skeletonKeyframes} 1.2s ease-in-out infinite; | |
} | |
`} | |
{...props} | |
/> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment