MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

ReactJS Program to Star Rating State with Explanation

ReactJS Medium State Management 27 views
This problem helps you practice core ReactJS fundamentals in a practical way. It builds intuition around rating, star, state. Let’s break it down step by step so you can implement it confidently.
Back to Questions

Problem Statement

Build a 5-star rating component where user can select a rating.

Input Format

No input.

Output Format

Render a React component.

Constraints

Store selected rating in state and render stars from it.

Code Solution

This explanation is written for learning purposes and to help beginners understand the concept clearly.
import React, { useState } from 'react'; function Star({ filled, onClick, label }) { return ( <button type='button' onClick={onClick} aria-label={label} style={{ width: 40, height: 40, borderRadius: 12, border: '1px solid #ddd', background: filled ? '#eafaf1' : '#fff', color: filled ? '#0b5' : '#999', fontSize: 18 }}> ★ </button> ); } export default function App() { const [rating, setRating] = useState(0); return ( <div style={{ padding: 16 }}> <h2 style={{ marginTop: 0 }}>Rate meetcode</h2> <div style={{ display: 'flex', gap: 8 }}> {Array.from({ length: 5 }, (_, i) => { const value = i + 1; return <Star key={value} filled={value <= rating} onClick={() => setRating(value)} label={'Rate ' + value} />; })} </div> <div style={{ marginTop: 10, color: '#555' }}>Selected: {rating || 'None'}</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