ReactJS Program to Badge Component With Color with Explanation
ReactJS
Easy
Component Design
27 views
1 min read
84 words
This problem helps you practice core ReactJS fundamentals in a practical way. It builds intuition around component, badge, color. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Make a Badge component that supports colors: green, gray, red.
Input Format
No input.
Output Format
Render a React component.
Constraints
Map prop values to styles.
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
import React from 'react';
export function Badge({ tone = 'gray', children }) {
const tones = {
green: { background: '#eafaf1', color: '#0b5', border: '1px solid #b7f0d0' },
gray: { background: '#f3f4f6', color: '#374151', border: '1px solid #e5e7eb' },
red: { background: '#ffe8ea', color: '#c1121f', border: '1px solid #ffc2c7' }
};
return (
<span style={{ display: 'inline-block', padding: '4px 10px', borderRadius: 999, fontSize: 12, fontWeight: 700, ...tones[tone] }}>
{children}
</span>
);
}
export default function App() {
return (
<div style={{ display: 'flex', gap: 10, padding: 16 }}>
<Badge tone='green'>NEW</Badge>
<Badge>INFO</Badge>
<Badge tone='red'>ALERT</Badge>
</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).
Solution Guide
Problem
Make a Badge component that supports colors: green, gray, red.
Input / Output
Output
Render a React component.
Constraints
Map prop values to styles.
Details
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).
Official Solution
import React from 'react';
export function Badge({ tone = 'gray', children }) {
const tones = {
green: { background: '#eafaf1', color: '#0b5', border: '1px solid #b7f0d0' },
gray: { background: '#f3f4f6', color: '#374151', border: '1px solid #e5e7eb' },
red: { background: '#ffe8ea', color: '#c1121f', border: '1px solid #ffc2c7' }
};
return (
<span style={{ display: 'inline-block', padding: '4px 10px', borderRadius: 999, fontSize: 12, fontWeight: 700, ...tones[tone] }}>
{children}
</span>
);
}
export default function App() {
return (
<div style={{ display: 'flex', gap: 10, padding: 16 }}>
<Badge tone='green'>NEW</Badge>
<Badge>INFO</Badge>
<Badge tone='red'>ALERT</Badge>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!