Skip to content
Tutorials Center
My learning

Topics

Lesson 124 of 132 ยท Projects

Project: Color Palette Generator

Build a colour palette generator in React with HSL colour math, locking swatches, keyboard shortcuts, copy to clipboard and WCAG contrast checking.

Colour tools are a great React exercise because the interesting part is not the UI, it is the data model. A colour is three numbers. A palette is a list of colours. Everything else (hex codes, text colour, accessibility ratings) can be calculated from those numbers during render.

In this project you will build a palette generator in three stages. First you will write the colour maths as plain functions and render harmony palettes from one base colour. Then you will build a generator with locked swatches, a keyboard shortcut and copy-to-clipboard. Finally you will add a contrast checker based on the WCAG formula. You will use state, effects with cleanup, lists and keys and the accessibility ideas from the accessibility lesson.

Why HSL?

Hex codes such as #3b82f6 are hard to reason about: what is "a bit lighter"? HSL describes a colour with three intuitive numbers: hue (0-360, the position on the colour wheel), saturation (0-100%, how vivid) and lightness (0-100%). To make a colour lighter you raise l. To get its complement you add 180 to h. Browsers understand hsl(210 80% 50%) directly in CSS, so we only need a conversion to hex for display and copying.

Stage 1: colour maths and harmony palettes

Pure functions first, with no React. hslToHex converts, contrastRatio implements the WCAG formula (it compares the relative luminance of two colours, where green counts the most because our eyes are most sensitive to it) and readableText chooses black or white text for a background by picking whichever has the higher contrast.

The component then builds palettes by hue offsets from a base hue. Complementary uses 0, 180; analogous uses small steps; triadic uses 0, 120, 240. Nothing is stored except the base hue and the scheme: the swatches are derived.

Stage 1: colour maths and harmonies

Open the console panel to see the maths working alone: red is #ff0000, blue is #0000ff, and black on white has the maximum contrast ratio of 21. Move the slider and watch the text colour flip between black and white as the background changes: that decision is a pure calculation, not state.

Stage 2: random palettes with locks, keys and copy

The usual generator shape is a row of swatches; pressing Space regenerates every swatch that is not locked. State is a list of swatches, each with its HSL values, a stable id and a locked flag. Regenerating returns a new list where unlocked swatches get new random values and locked ones are kept as they are.

Keyboard shortcuts are an outside system, so they live in an effect with a cleanup that removes the listener (effect cleanup). Using the functional form setSwatches((current) => ...) means the listener never reads stale state, so the effect has no dependencies and subscribes only once. The listener ignores presses on buttons, so Space on a focused button does not fire twice.

Copying uses navigator.clipboard, which is blocked in this sandbox. The try/catch shows a helpful fallback instead of crashing.

Stage 2: locks, Space key and copy

Lock two swatches, then press Space a few times: only the unlocked ones change. Three details matter. The swatch id never changes, so each swatch keeps its identity when its colour changes (a good key, see lists and keys). The lock button uses aria-pressed, so screen readers announce it as a toggle. And readableText here uses a quick luminance threshold of 0.179, which is the point where black and white text have equal contrast: a handy shortcut.

Stage 3: a WCAG contrast checker

Pretty is not enough: text must be readable. The Web Content Accessibility Guidelines (WCAG) require a contrast ratio of at least 4.5:1 for normal text (level AA), 3:1 for large text, and 7:1 for the stricter AAA level. The checker below lets you pick a text colour and a background from a palette and shows the ratio and the verdict for each level. It stores only the two choices; the ratio and the verdicts are calculated.

Stage 3: contrast checker

Try Sky on Mint: the two are both light, so every verdict fails, even though the combination might look "fresh" on a mood board. This is exactly why generators should show contrast next to the swatches. Never rely on colour alone to carry meaning either: add text or icons (accessibility).

Ideas to extend it

  • Combine the stages: show the contrast verdict of every swatch against black and white inside the generator.
  • Keep the palette in the URL hash (#264653-2a9d8f-...) so palettes can be shared, as in the blog project.
  • Add a "shades" row: the same hue with lightness 10%, 20% ... 90%, produced with a map and hslToHex.
  • Export the palette as CSS custom properties text in a <pre> block with a copy button.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is HSL convenient for generating palettes?

    HSL separates the position on the colour wheel from vividness and brightness, so palette rules become simple arithmetic. Hex or RGB hide that structure.
  2. 2. Why does the Space key listener use setSwatches(regenerate) with an empty dependency array?

    Passing a function to the setter makes React supply the current state, so the effect does not need swatches in its dependencies. The cleanup removes the listener on unmount.
  3. 3. What minimum contrast ratio does WCAG AA require for normal-sized text?

    4.5:1 is the AA minimum for normal text. Large text needs 3:1, and level AAA asks for 7:1.
  4. 4. Why is the clipboard call wrapped in try/catch?

    The clipboard API needs a permitted context and can fail. Handling the rejection lets the app show a fallback message instead of an unhandled error.

Summary

  • Model colours as HSL numbers; derive hex codes, text colours and ratings during render.
  • Keep colour maths in pure functions: they are easy to check in the console and to test.
  • Locks are a boolean per swatch; stable ids keep swatches' identity when values change.
  • Subscribe to keyboard events in an effect and always remove the listener in the cleanup.
  • Copy with navigator.clipboard inside try/catch, and check contrast with the WCAG formula (4.5:1 for normal text at AA).

Next: Project: 15 Puzzle and Flappy Bird