UNPKG

@eureca/eureca-ui

Version:

UI component library of Eureca's user and admin apps

62 lines (56 loc) 1.58 kB
import React, { useState } from 'react'; import styled, { css } from 'styled-components'; import PropTypes from 'prop-types'; import placeholder from '../../assets/images/avatar_placeholder.svg'; const AvatarContainer = styled.div` ${({ size, color, onClick }) => css` display: inline-block; box-sizing: border-box; width: ${size}px; height: ${size}px; line-height: ${size}px; cursor: ${typeof onClick === 'function' ? 'pointer' : 'inherit'}; border: 2px solid ${color || 'transparent'}; border-radius: 50%; overflow: hidden; img { width: 100%; height: 100%; object-fit: cover; } `} `; function Avatar({ name = '', src = placeholder, color = 'transparent', size = 48, style = null, containerStyle = null, ...props }) { const [isLoaded, setLoaded] = useState(); const [isError, setError] = useState(); const imageIsOk = isLoaded || !isError; if (isError) console.warn('Unable to load avatar at', src); return ( <AvatarContainer color={color} size={size} style={containerStyle} {...props}> <img src={src || placeholder} alt={`${name} avatar`} style={imageIsOk ? style : { display: 'none' }} onLoad={() => setLoaded(true)} onError={() => setError(true)} /> {!imageIsOk && <img src={placeholder} alt="Unloaded avatar" />} </AvatarContainer> ); } Avatar.propTypes = { name: PropTypes.string, src: PropTypes.string, color: PropTypes.string, size: PropTypes.number, style: PropTypes.object, }; export { Avatar };