Skip to content

Instantly share code, notes, and snippets.

@Deep-Codes
Created September 4, 2021 20:35
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 Deep-Codes/d1bf7cb4f8c69401f6a95ac222dbfd9c to your computer and use it in GitHub Desktop.
Save Deep-Codes/d1bf7cb4f8c69401f6a95ac222dbfd9c to your computer and use it in GitHub Desktop.
loading + blur
import React from 'react';
import Image from 'next/image';
interface Props {
width: number;
height: number;
src: string;
alt: string;
}
const CustomImage: React.FC<Props> = ({ width, height, src, alt }) => {
const ref = React.useRef(null);
const imageRef = React.useRef(null);
React.useEffect(() => {
if (typeof window !== undefined) {
const ctx = document.getElementById('main-container');
if (ctx) {
let w = ctx.offsetWidth <= 760 ? ctx.offsetWidth - 32 : ctx.offsetWidth;
const ratio = width / height;
ref.current.style.height = `${w / ratio}px`;
}
}
}, []);
const removeLoader = () => {
ref.current.style.display = 'none';
imageRef.current.classList.add('image-blur');
};
return (
<div className='relative my-10'>
<div ref={imageRef}>
<Image
width={width}
height={height}
alt={alt}
src={src}
onLoadingComplete={() => removeLoader()}
/>
</div>
<div ref={ref} className='skeleton absolute top-0 left-0' />
<p className='text-center my-0 text-sm text-gray-1000'>{alt}</p>
</div>
);
};
export default CustomImage;
.skeleton {
width: 100%;
border-radius: 5px;
background-image: linear-gradient(
270deg,
var(--gray1),
var(--gray3),
var(--gray3),
var(--gray1)
);
background-size: 400% 100%;
-webkit-animation: sk 6s ease-in-out infinite;
animation: sk 6s ease-in-out infinite;
}
@keyframes sk {
0% {
background-position: 200% 0;
}
100% {
background-position: -200% 0;
}
}
.image-blur {
animation: blur 2s ease 0s;
-webkit-animation: blur 2s ease 0s;
-moz-animation: blur 2s ease 0s;
}
@keyframes blur {
0% {
-webkit-filter: blur(10px);
-moz-filter: blur(10px);
-o-filter: blur(10px);
-ms-filter: blur(10px);
}
100% {
-webkit-filter: blur(0px);
-moz-filter: blur(0px);
-o-filter: blur(0px);
-ms-filter: blur(0px);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment