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

72 lines
1.4 KiB
TypeScript
Raw Normal View History

import React from 'react';
2019-12-08 01:13:08 +05:30
import clsx from 'clsx';
import { ComponentLoader } from 'app/components/ui/loader';
import { SKIN_LIGHT } from 'app/components/ui';
import styles from './imageLoader.scss';
export default class ImageLoader extends React.Component<
{
2019-12-07 16:58:52 +05:30
src: string;
alt: string;
ratio: number; // width:height ratio
onLoad?: Function;
},
{
2019-12-07 16:58:52 +05:30
isLoading: boolean;
}
> {
state = {
isLoading: true,
};
2019-12-10 13:17:32 +05:30
componentDidMount() {
this.preloadImage();
}
preloadImage() {
const img = new Image();
img.onload = () => this.imageLoaded();
img.onerror = () => this.preloadImage();
img.src = this.props.src;
}
imageLoaded() {
this.setState({ isLoading: false });
if (this.props.onLoad) {
this.props.onLoad();
}
}
render() {
const { isLoading } = this.state;
const { src, alt, ratio } = this.props;
return (
<div className={styles.container}>
<div
style={{
height: 0,
paddingBottom: `${ratio * 100}%`,
}}
/>
{isLoading && (
<div className={styles.loader}>
<ComponentLoader skin={SKIN_LIGHT} />
</div>
)}
<div
2019-12-08 01:13:08 +05:30
className={clsx(styles.image, {
[styles.imageLoaded]: !isLoading,
})}
>
<img src={src} alt={alt} />
</div>
</div>
);
}
}