accounts-frontend/packages/app/components/ui/loader/ImageLoader.tsx

60 lines
1.5 KiB
TypeScript
Raw Permalink Normal View History

import React, { ComponentType, useEffect, useState } from 'react';
2019-12-08 01:13:08 +05:30
import clsx from 'clsx';
import { SKIN_LIGHT } from 'app/components/ui';
import ComponentLoader from './ComponentLoader';
import styles from './imageLoader.scss';
interface Props {
2020-05-24 04:38:24 +05:30
src: string;
alt: string;
ratio: number; // width:height ratio
onLoad?: () => void;
}
2020-05-24 04:38:24 +05:30
const ImageLoader: ComponentType<Props> = ({ src, alt, ratio, onLoad = () => {} }) => {
const [isLoading, setIsLoading] = useState<boolean>(true);
useEffect(() => {
function preloadImage() {
const img = new Image();
img.onload = () => {
setIsLoading(false);
onLoad();
};
img.onerror = preloadImage;
img.src = src;
}
preloadImage();
}, [src]);
return (
<div className={styles.container}>
<div
style={{
height: 0,
paddingBottom: `${ratio * 100}%`,
}}
/>
{isLoading && (
<div className={styles.loader}>
<ComponentLoader skin={SKIN_LIGHT} />
</div>
)}
<div
className={clsx(styles.image, {
[styles.imageLoaded]: !isLoading,
})}
>
<img src={src} alt={alt} />
</div>
</div>
2020-05-24 04:38:24 +05:30
);
};
export default ImageLoader;