Skip to content

Instantly share code, notes, and snippets.

@hrdtbs
Last active June 26, 2020 12:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hrdtbs/a0fc073dca3890421bd34b280936268f to your computer and use it in GitHub Desktop.
Save hrdtbs/a0fc073dca3890421bd34b280936268f to your computer and use it in GitHub Desktop.
/** @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