Back to Blog
Lesson 4 of the React Fundamentals: Build Modern UIs from Scratch course
ReactJune 24, 20264 min read

Mastering JSX Syntax: Writing Declarative React Components

Learn how to write valid JSX, embed JavaScript expressions, and handle DOM attributes correctly to build clean, declarative React components.

ReactJSXFrontendJavaScriptWeb Development

Previously in this course, we set up our development environment using Vite. Now that your workspace is ready, it's time to dive into the core of how we describe UI in React: JSX.

JSX stands for JavaScript XML. It’s a syntax extension that allows us to write code that looks like HTML directly inside our JavaScript functions. While it might look like HTML, it’s actually a syntactic sugar for React.createElement() calls, which makes our code much more readable and maintainable.

Writing Valid JSX

When you write JSX, you are essentially describing what the UI should look like. However, because JSX is ultimately transformed into JavaScript, there are strict rules you must follow.

The most important rule is that JSX must have a single parent element. If you want to return multiple elements, you must wrap them in a container.

JSX
// ❌ Invalid: Multiple top-level elements
return (
  <h1>Movie Title</h1>
  <p>Description</p>
);

// ✅ Valid: Wrapped in a single parent(like a div or Fragment)
return (
  <div>
    <h1>Movie Title</h1>
    <p>Description</p>
  </div>
);

If you don't want to add an extra <div> to your DOM tree, you can use a Fragment—an empty tag <>...</>—which tells React to group elements without adding a wrapper node to the rendered output.

Embedding JavaScript Expressions

The true power of JSX lies in its ability to seamlessly integrate with JavaScript. You can embed any valid JavaScript expression inside JSX by wrapping it in curly braces {}.

Think of curly braces as an "escape hatch" from JSX back into the world of JavaScript.

JSX
const movieTitle = "Inception";
const releaseYear = 2010;

function MovieHeader() {
  return (
    <header>
      {/* We can embed strings, numbers, and variables */}
      <h1>{movieTitle.toUpperCase()}</h1>
      <p>Released in: {releaseYear}</p>
      
      {/* We can even run logic */}
      <p>Age: {new Date().getFullYear() - releaseYear} years old</p>
    </header>
  );
}

JSX vs. HTML Attributes

JSX looks like HTML, but it is not HTML. Because it is JavaScript, some attribute names differ to avoid conflicts with reserved JavaScript keywords.

  1. className instead of class: Since class is a reserved keyword in JavaScript, React uses className to define CSS classes.
  2. htmlFor instead of for: Similar to class, for is a reserved keyword. Use htmlFor for <label> elements.
  3. CamelCase attributes: Attributes like tabindex become tabIndex, and onclick becomes onClick.

Example: The Movie Browser Card Let’s advance our movie browser project by creating a basic card component that uses these principles.

JSX
function MovieCard() {
  const title = "The Matrix";
  const isAvailable = true;

  return (
    <div className="movie-card">
      <h2 style={{ color: CE9178">'blue' }}>{title}</h2>
      <button disabled={!isAvailable}>
        {isAvailable ? "Watch Now" : "Coming Soon"}
      </button>
    </div>
  );
}

Notice the style attribute above: it takes an object ({{ color: 'blue' }}) rather than a CSS string. The outer braces indicate we are entering JavaScript, and the inner braces define the object literal.

Hands-on Exercise

Open your Vite project and navigate to your App.jsx file. Replace the default boilerplate with a simple movie display:

  1. Create a variable movieName with any movie title.
  2. Create an imageUrl variable with a placeholder URL.
  3. Return a <div> that contains an <h1> with the movie name, and an <img> tag.
  4. Remember: JSX requires images to have a self-closing tag (<img />) and a className instead of a class.

Common Pitfalls

  • Missing Self-Closing Tags: In HTML, tags like <br> or <img> don't always need a closing slash. In JSX, every tag must be closed. Use <br /> or <img src="..." />.
  • Rendering Objects: You cannot render a raw JavaScript object directly in JSX. If you try to do {user}, React will throw an error. You must render specific properties, like {user.name}.
  • Boolean values: Booleans like true or false are not rendered as text in JSX. If you want to show a status, use a ternary operator: {isOnline ? "Online" : "Offline"}.

Recap

JSX is our primary tool for defining UI. It allows us to write declarative code that maps directly to our components. By mastering the use of curly braces for expressions and understanding the nuances of attribute naming (like className), you've taken the first step toward building complex, dynamic interfaces.

Up next, we will move beyond single components and start Creating Static Components to build the skeleton of our movie browser.

Similar Posts