Components and JSX

Set attributes and styles

Pass strings, expressions, booleans, and style objects through JSX properties.

A quoted JSX property is a string. Braces pass a JavaScript value:

<img
  src={avatarUrl}
  alt={name}
  width={160}
  height={160}
  hidden={!avatarUrl}
/>

Here src and alt receive strings, width and height receive numbers, and hidden receives a boolean.

Do not quote an expression:

<img src="{avatarUrl}" alt="Profile" />

That sends the literal text {avatarUrl} to the browser.

Use CSS classes for most styling:

<p className={saved ? 'status status--saved' : 'status'}>
  {saved ? 'Saved' : 'Not saved'}
</p>

Inline styles receive an object with camelCase properties:

<div style={{ width: `${progress}%` }} />

Inline styles are useful when a value genuinely comes from data. Classes are usually clearer for hover, focus, media queries, and a shared visual system.

React does not make inaccessible attributes safe. An image still needs useful alt text, and a clickable div is still the wrong control. Prefer semantic elements before adding behavior and styles.

Change saved and progress, then inspect the actual class and style attributes in the DOM.

Lesson completed

Take this course offline

Get every free book, course edition, and software download.

Get the download library →