UNPKG

@eureca/eureca-ui

Version:

UI component library of Eureca's user and admin apps

101 lines (88 loc) 2.41 kB
import React, { useState, useRef, useEffect } from 'react'; import PropTypes from 'prop-types'; import { Box } from '@material-ui/core'; import { FaPlus } from 'react-icons/fa'; import { Flex } from '../Flex'; import { Avatar } from './avatar'; import { colors } from '../../theme/colors'; const AvatarUpload = ({ onClick, src, onUpload, width, height, maxSize, ...props }) => { const [srcAvatar, setSrcAvatar] = useState(src); useEffect(() => { setSrcAvatar(src); }, [src]); const refFileInput = useRef(); function handleClick() { refFileInput.current.click(); if (typeof onClick === 'function') { onClick(); } } function handleUpload(event) { const file = event.target?.files[0]; if (file) { const reader = new FileReader(); const maxAllowedSize = maxSize * 1024 * 1024; if (file.size > maxAllowedSize) { onUpload({ error: 'bad size' }); return; } reader.onload = () => { const img = new Image(); const dataURL = reader.result; img.src = dataURL; img.onload = () => { if (img.width < width || img.height < height) { onUpload({ error: 'bad dimensions' }); return; } setSrcAvatar(dataURL); onUpload({ avatar: file }); }; }; reader.readAsDataURL(file); } } return ( <Box display="inline" position="relative" style={{ cursor: 'pointer' }}> <Avatar src={srcAvatar} color={colors.green1} onClick={handleClick} {...props} /> <input ref={refFileInput} accept=".png, .jpg, .jpeg" type="file" onChange={handleUpload} style={{ display: 'none' }} /> <Flex justifyCenter alignCenter position="absolute" bottom="50%" left="75%" bgcolor={colors.gray2} width={24} height={24} borderRadius="50%" onClick={handleClick} > <FaPlus color={colors.white} size={9} /> </Flex> </Box> ); }; AvatarUpload.defaultProps = { src: '', width: 48, height: 48, maxSize: 8, onClick: () => {}, onUpload: () => {}, }; AvatarUpload.propTypes = { src: PropTypes.string, width: PropTypes.number, height: PropTypes.number, maxSize: PropTypes.number, onClick: PropTypes.func, onUpload: PropTypes.func, }; export { AvatarUpload };