Avatar With Fallback
ReactJS
Medium
7 views
Problem Description
Create an Avatar that shows an image, but falls back to initials if image is missing.
Output Format
Render a React component.
Constraints
Handle image error state inside the component.
Official Solution
import React, { useState } from 'react';
export function Avatar({ name, src, size = 56 }) {
const [broken, setBroken] = useState(false);
const initials = name
.split(' ')
.filter(Boolean)
.slice(0, 2)
.map((part) => part[0].toUpperCase())
.join('');
const common = {
width: size,
height: size,
borderRadius: '50%',
display: 'grid',
placeItems: 'center',
fontWeight: 700,
background: '#0b5',
color: '#fff'
};
if (!src || broken) {
return <div style={common} aria-label={name}>{initials}</div>;
}
return (
<img
src={src}
alt={name}
width={size}
height={size}
style={{ ...common, objectFit: 'cover' }}
onError={() => setBroken(true)}
/>
);
}
export default function App() {
return (
<div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: 16 }}>
<Avatar name='Meetcode Learner' src='' />
<div>
<strong>Meetcode Learner</strong>
<div style={{ color: '#555' }}>Practicing CSS</div>
</div>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!