MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

ReactJS Program to Avatar With Fallback with Explanation

ReactJS Medium Component Design 26 views
This problem helps you practice core ReactJS fundamentals in a practical way. It builds intuition around image, avatar, react. Let’s break it down step by step so you can implement it confidently.
Back to Questions

Problem Statement

Create an Avatar that shows an image, but falls back to initials if image is missing.

Input Format

No input.

Output Format

Render a React component.

Constraints

Handle image error state inside the component.

Code Solution

This explanation is written for learning purposes and to help beginners understand the concept clearly.
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> ); }

Output Example

No sample I/O is provided for this question.

Common Mistakes

- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).

Notes & Extra Practice

Solutions (0)

No solutions submitted yet. Be the first!

Prev Next