React: Style objects from data

Compute an element's style from data, which is what style objects are for.

What to build

A status box whose background colour and text depend on a level.

Requirements

  • Keep LEVELS and level. Render a div with the class status whose style sets backgroundColor to LEVELS[level].colour, color to white and padding to 12 (pixels).
  • Inside it, a strong with the level's label and a span with the text level (a space before the word).

Constraints

Use a style object, not a style string, and read the values from LEVELS.

Example

With level "warning", the box is orange (#C16B3C) with white text "Warning level".

Why it works

Because style is an object, its values can come straight from data, so the same component shows any level correctly.

Hints

Hint 1

Look up the colour with LEVELS[level] and use it in style={{ backgroundColor: colour }}.

Hint 2

Numbers in a style object mean pixels: padding: 12.

Solution

Show one correct solution (try it yourself first)
const LEVELS = {
  ok: { label: "OK", colour: "#2E7D32" },
  warning: { label: "Warning", colour: "#C16B3C" },
  danger: { label: "Danger", colour: "#B3261E" },
};
const level = "warning";

export default function App() {
  const info = LEVELS[level];
  return (
    <div className="status" style={{ backgroundColor: info.colour, color: "white", padding: 12 }}>
      <strong>{info.label}</strong>
      <span> level</span>
    </div>
  );
}

Lesson: JSX: HTML inside JavaScript →