DOM & Browsermedium
Build a StarRating component
Controlled component: props `value` (1–maxStars) and `onChange(next: number)`. Render `maxStars` clickable stars (or buttons). Clicking star `k` sets rating to `k`. Optional follow-up: discuss hover preview without committing value.
Asked at Google, Stripe, Airbnb
Answer
function StarRating({ value, onChange, maxStars = 5 }) { return ( <div role="group" aria-label="Rating"> {Array.from({ length: maxStars }, (_, i) => { const star = i + 1 const filled = star <= value return ( <button key={star} type="button" aria-pressed={filled} aria-label={`${star} star${star > 1 ? 's' : ''}`} onClick={() => onChange(star)} > {filled ? '★' : '☆'} </button> ) })} </div> ) } // Usage function Demo() { const [rating, setRating] = React.useState(0) return <StarRating value={rating} onChange={setRating} /> } // Hover preview pattern: keep committed `value` and local `hover` state; // render filled state from hover ?? value; clear hover on mouseLeave. // Accessibility improvements in a longer interview: // - roving tabindex for arrow-key navigation between stars // - ensure focus outline is visible
Source: common React screen interview