Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 1.5 — Inline Styles and Class Names in JSX
React · Example 2 of 2

Conditional class names, two ways

The template literal leaves a trailing space ("task ") when the condition is false; the helper produces clean strings and handles any number of optional classes. A prop written with no value, like done, means done={true}.

In JSX the style attribute takes a JavaScript object with camelCase property names (numbers become pixels for most properties), and className takes a string you can build from conditions to switch CSS classes on and off.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Make a Swatch component that takes a color prop and shows a 40×40 square of that colour with rounded corners, using a style object.

02

Make a Button that gets the class btn, plus btn-primary when primary is true and btn-disabled when disabled is true.

Explain it without notes

01

How is the style attribute in JSX different from HTML's?

02

When does React add px to a number in a style object?

03

Show two ways to add a class only when a condition is true.

04

When would you choose an inline style over a class?

Conditional class names, two ways

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

"task done" "task done"
"task " "task urgent"
"task " "task"