aboutsummaryrefslogtreecommitdiff
path: root/src/components/Image/Image.tsx
blob: 7736e8adb3b2b1d094bbddec19a7e656808bc111 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import React, { useState, useCallback } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import CircularProgress from '@material-ui/core/CircularProgress';
import ErrorIcon from '@material-ui/icons/BrokenImage';

interface PropTypes {
  src?: string;
  alt?: string;
  className?: string;
}

const useStyles = makeStyles(theme => ({
  container: {
    width: '100%',
    height: '100%',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center'
  }
}));

type Status = 'success' |'loading' | 'error';

const Image: React.FC<PropTypes> = ({ src, alt, className }) => {
  const classes = useStyles();
  const [status, setStatus] = useState<Status>('loading');

  const handleLoad = useCallback((): void => {
    setStatus('success');
  }, [setStatus]);

  const handleError = useCallback((): void => {
    setStatus('error');
  }, [setStatus]);

  const image = (
    <img
      src={src}
      alt={alt}
      className={className}
      style={{ display: status === 'success' ? 'inline' : 'none' }}
      onLoad={handleLoad}
      onError={handleError}
    />
  );

  return (
    <>
      {src && image}
      {
        status !== 'success' && (
          <div className={classes.container}>
            {
              (status === 'error' || !src)
              ? <ErrorIcon fontSize="large" />
              : <CircularProgress color="primary" />
            }
          </div>
      )}
    </>
  );
};

export default Image;