A set of clickable stars that lets users express a rating. Product reviews, movie ratings, driver feedback — every app with user-generated scores needs one. The challenge is not rendering a star. It is handling hover previews that don't commit, half-star precision, keyboard input without visual focus indicators that misalign with the mouse, and making all of it accessible to screen readers.
FrontendX Engineering · System Design Series #12
Before writing a single line of code, let us define what we are building. The star rating component looks simple — five stars, click one, done. But the edge cases are what make it interesting.
The star rating is a controlled input component. It takes a value and an onChange callback, renders a set of stars, and delegates the interaction logic to the consumer. The internal complexity is modest compared to an autocomplete or a dropdown menu — the state surface is small, and there is no asynchronous fetching.
The key architectural decision is how to handle the hover preview state. Hover values are ephemeral — they change on every mouseEnter/mouseLeave and must not trigger the consumer's onChange callback. They exist only as internal state, separate from the committed value.
Render all stars as a single SVG with individual <polygon> elements grouped in one root. This is memory-efficient — one SVG node instead of five — but makes it harder to handle individual star events. You must calculate which star was clicked from the mouse coordinates, which is fragile across reflows.
Use native <button> elements with Unicode star characters (★ ☆) or CSS clip-path. Buttons have built-in focus management, click handling, and keyboard support. However, Unicode stars are inconsistent across operating systems, and CSS clip-path does not allow half-star rendering.
Each star is an independent SVG element with role="radio". The group is wrapped in a role="radiogroup" container. This gives us precise event handling per star, native ARIA semantics, and full control over the star appearance via SVG paths. Half-stars use an SVG clip-path to fill only the left side.
Single SVG node, fragile coordinate math. Rejected.
Great a11y but inconsistent rendering, no half-stars. Rejected.
Precise events, ARIA semantics, full visual control. Chosen.
role="radio" mirrors the HTML spec's own radio button pattern. Each star is an option in a set where exactly one can be selected at any time. This maps naturally to the radiogroup ARIA pattern, giving us keyboard navigation and screen reader announcements essentially for free.The star rating has one of the smallest state surfaces in this series. Three state variables control the entire interaction.
onChange. In controlled mode, this comes from the consumer. In uncontrolled mode, it lives in internal state.onMouseEnter, reset to null on onMouseLeave. When non-null, the component renders stars based on this value instead of the committed value. This is purely internal — the consumer never sees it.tabIndex=0 on the focused element and tabIndex=-1 on all others. This value manages that rotation.isFocused flag. Focus management is handled entirely through the radiogroup pattern's roving tabindex. Adding a separate boolean would introduce a source of truth conflict with the DOM focus state.The API is deliberately small. A star rating is a simple concept, and the interface should reflect that.
value is provided, the component is controlled and onChange is required. If only defaultValue is given, the component manages its own state internally.The component works in controlled, uncontrolled, and read-only modes with a minimal API surface:
Let us walk through the implementation layer by layer. The star rating has four subsystems: the SVG rendering engine, the hover/click interaction model, the half-star math, and the keyboard navigation handler.
Each star is an SVG element with a single path — the standard five-pointed star polygon. The path is the same for every star; only the fill and stroke change based on the star's state. I use a small path string rather than separate filled/unfilled SVGs to minimize the markup per star.
The fill prop accepts three values: "empty", "half", or "full". The half state uses an SVG <clipPath> that masks the right half of the star. This is more reliable than rendering two overlapping paths because it guarantees pixel-perfect alignment along the center line.
This is the trickiest interaction in the component. When the user hovers over a star, the component should show a preview — but not commit it. The preview is purely visual, driven by the internal hoverValue state. When the mouse leaves, the component reverts to the committed value.
The display logic is a simple priority check: if hoverValue is non-null, render based on that; otherwise, render based on the committed value. This ensures the preview is ephemeral and never leaks into the consumer's state.
Determining whether a star is empty, half, or full requires comparing the display value to the star's index. The logic is simple but easy to get wrong off-by-one.
For click handling with half-stars, I check the mouse's X coordinate relative to the star SVG's bounding box. If the click is in the left half (clientX < rect.left + rect.width / 2), the value rounds down to the nearest half. Otherwise, it rounds up. This matches the visual split line of the clip-path.
getBoundingClientRect at event time rather than caching it.The radiogroup pattern specifies that ArrowLeft and ArrowDown move focus to the previous item, and ArrowRight and ArrowUp move to the next item. Home and End jump to the first and last items. The focused item is marked with tabIndex=0 while all others have tabIndex=-1.
For half-star mode, the increment is 0.5 instead of 1. I use Math.round(value * 2) / 2 to avoid floating-point precision issues — a common pitfall when adding 0.1 repeatedly in JavaScript.
The data flow is straightforward because the star rating has no asynchronous operations. Every interaction is synchronous and local.
onMouseEnter fires. hoverValue is set to the star index + 1. Stars re-render with preview highlighting.
onMouseEnter fires on the new star. hoverValue updates. Previous star reverts to committed state.
If allowHalf, check click coordinates. If left half, value = index + 0.5. Otherwise, value = index + 1. onChange fires with the new value.
onMouseLeave fires on the container. hoverValue resets to null. Stars re-render based on committed value.
onKeyDown handler evaluates key and direction. value updates in 1.0 or 0.5 increments. The newly selected star gets tabIndex=0.
The key insight is that hover and click operate on two different state variables. Hover updates hoverValue (ephemeral). Click updates value (committed). The display layer merges both: use hoverValue ?? value as the effective rating for rendering. This pattern is identical to how an autocomplete shows a highlighted suggestion (ephemeral) vs. a selected suggestion (committed).
The star rating is a simple component, but hover events fire frequently — every pixel the mouse moves over a star triggers a re-render. Without care, this can cause jank.
Wrap the rendered star array in useMemo with [maxStars, size] as deps. The stars do not change shape or size between renders — only their fill state changes. Memoizing prevents recreating the SVG elements on every hover event.
Add contain: layout style to the radiogroup container. This tells the browser that changes inside the container do not affect the layout or style of elements outside it. The browser can skip recalculating styles and layout for the rest of the page on hover.
Inline SVG is faster than image-based stars (PNG or CSS sprite) because there is no HTTP request, no decoding step, and the browser can composite the SVG directly. The path data is small — approximately 120 bytes per star string — so the entire set of five stars costs less than 1 KB of transfer.
If the component uses hover transitions (e.g., a scale-up animation on hover), respect prefers-reduced-motion. The star rating should work without animations — the visual state change (fill color) is already sufficient feedback. I only add CSS transitions for the fill color, which is not affected by reduced-motion preferences.
onMouseEnter event, which is per-star, not per-pixel. This is much cheaper than an autocomplete's debounce cycle. A star rating with five stars generates at most 5 re-renders on hover, one per star, not one per pixel.The star rating has a smaller attack surface than a text input — no injection vectors, no network calls. But there are still a few things to consider.
[0, maxStars] range. A consumer passing value=100 should not break the rendering. Clamp on both the controlled value input and the internal state.name attribute, the rating is submitted as a hidden input value. A malicious user can modify that value via browser devtools. Validate the rating on the server — never trust client-side values.label prop is used as aria-label. If the consumer passes user-generated content as the label (e.g., a product name), React escapes it by default. Do not use dangerouslySetInnerHTML for labels.X-Frame-Options or Content-Security-Policy headers on the parent page.Testing the star rating is straightforward with React Testing Library and user-event. The key principle is the same as every other component: test behavior, not implementation.
The tests I consider essential:
onChange was called with 3, and the star has aria-checked="true".onChange was not called. The preview is purely visual.onChange fires with the correct values.getBoundingClientRect return value to control the click coordinates.onChange. The component should have a muted appearance.value=100 and verify the component renders all stars as filled without errors.Element.prototype.getBoundingClientRect mock. Set it to return specific dimensions so you can control whether the click lands on the left or right half. This is the only place where you need to mock a browser API — all other tests work with the user-event abstraction.The star rating is surprisingly complex from an accessibility standpoint. Visual stars convey no meaning to screen readers, and the hover interaction is invisible to keyboard users. The WAI-ARIA radiogroup pattern solves both problems.
The container element gets role="radiogroup" with an aria-label that describes the rating purpose (e.g., "Rate this product"). Each star gets role="radio" with aria-checked indicating whether it is selected. The screen reader announces something like "3 stars, radio button, checked" when the user focuses a star.
I use the roving tabindex pattern. Exactly one star has tabIndex=0 (the currently focused or last selected star). All others have tabIndex=-1. When the user presses ArrowRight, the component moves tabIndex=0 to the next star and calls focus() on it. This is the standard pattern for widget selection controls.
When the rating changes, screen readers should announce the new value. I use an aria-live="polite" region updated via a useEffect that watches the committed value. The announcement reads "Rating: 4 out of 5 stars." This is subtle but important — without it, keyboard users hear the individual star labels but never know the overall value.
Mouse users get hover previews; keyboard users get arrow keys. Both interactions produce identical visual feedback — stars highlight in real-time. The only difference is that hover previews are ephemeral (disappear on mouse leave) while keyboard navigation commits the value immediately. This asymmetry is by design: mouse users can explore without committing, while keyboard users expect each keypress to produce a permanent change.
In right-to-left locales, ArrowLeft should increase the rating and ArrowRight should decrease it. The component checks the dir attribute on the container and reverses the keyboard mapping accordingly. The star rendering itself is direction-neutral — a filled star is the same visual in any language.
Try the full implementation in a WebContainer playground. You can edit the code and see changes instantly — experiment with different star counts, half-star mode, and keyboard behavior.
Try these interactions: hover over stars to see the preview, click to commit a rating, enable half-star mode and click the left side of a star, use ArrowRight and ArrowLeft to navigate with the keyboard, and test with a screen reader to hear the radiogroup announcements.
hoverValue lives only in the component; value is the consumer's source of truth. Never call onChange from a hover handler.getBoundingClientRect at click time to determine whether the user clicked the left or right half of a star. Cache nothing — bounding boxes shift on scroll.value=100 or value=-5 should never crash the component. Clamp input values to [0, maxStars] and render gracefully.The star rating is the simplest component in this series by state count — three variables drive the entire interaction. But simplicity does not mean trivial. The hover/click split, the half-star clip-path, the keyboard roving tabindex, and the ARIA radiogroup wiring all require careful thought. The result is a component that looks like five shiny stars on the surface and handles every input modality underneath.