Jamie Balfour

Welcome to my personal website.

Find out more about me, my personal projects, reviews, courses and much more here.

Part 3.1Writing JSX

JSX is a syntax extension that lets JavaScript files contain HTML-like markup. The build tool transforms it into JavaScript before the browser runs it.

JavaScript expressions

Use braces to insert a JavaScript expression. An expression produces a value; statements such as if and for cannot be placed directly inside JSX.

JSX
function TaskSummary() {
  const remaining = 3;
  const taskWord = remaining === 1
    ? "task"
    : "tasks";

  return (
    <p className="task-summary">
      {remaining} {taskWord} remaining
    </p>
  );
}

Differences from HTML

JSX is stricter than HTML: close every element, return one parent and use camelCase attribute names. Write className instead of class, htmlFor instead of for, and onClick instead of onclick.

For example, this is ordinary HTML:

HTML
<section class="profile-card featured">
  <label for="display-name">
    Display name
  </label>
  <input
    id="display-name"
    class="profile-card__input"
  >
  <button
    class="button button--primary"
    onclick="saveProfile()"
  >
    Save profile
  </button>
</section>

The equivalent JSX uses React's property names and passes a function to the event prop:

JSX
<section className="profile-card featured">
  <label htmlFor="display-name">
    Display name
  </label>
  <input
    id="display-name"
    className="profile-card__input"
  />
  <button
    className="button button--primary"
    onClick={saveProfile}
  >
    Save profile
  </button>
</section>

Multiple CSS classes remain one space-separated string. React does not change how the browser applies those classes; only the JSX property is named className.

Dynamic attributes

Quotes create a literal string; braces use a JavaScript value. Inline style accepts an object, although a CSS class is usually easier to maintain.

JSX
<img
  src={imageUrl}
  alt={`${name}'s profile`}
  className="avatar avatar--large"
/>

Reading JSX precisely

src={imageUrl} reads a variable. In contrast, className="avatar" always uses the literal text avatar. The alt value uses a template literal inside braces, so it is recalculated when the component renders.

Expressions may call functions or use array methods, but rendering must remain pure. Do not start a request, change the DOM or alter another value inside the braces.

Challenge: build a profile card

Create a ProfileCard with variables for a person's name, job title and years of experience. Render a heading, paragraph and image. Show year for one year and years otherwise.

Hint

Use braces for each variable and a ternary expression for the singular or plural word.

Feedback 👍
Comments are sent via email to me.