🔥 0
0
Lesson 2 of 9 15 min +75 XP

JSX Basics

JSX is a syntax extension for JavaScript that looks like HTML but works inside your JavaScript code. It's not required to use React, but it makes writing components much more intuitive.

What is JSX?

JSX stands for JavaScript XML. It allows you to write markup directly in your JavaScript:

// This is JSX
const element = <h1>Hello, World!</h1>;

// It compiles to this JavaScript
const element = React.createElement('h1', null, 'Hello, World!');

Under the hood, JSX is just syntactic sugar for React.createElement() calls. The build tool (like Vite or Babel) transforms JSX into regular JavaScript.

JSX Rules

1. Return a Single Root Element

Components must return a single element. Use a wrapper

or a Fragment (<>...):

// ❌ Wrong - multiple root elements
function Card() {
  return (
    <h1>Title</h1>
    <p>Description</p>
  );
}

// ✅ Correct - using Fragment
function Card() {
  return (
    <>
      <h1>Title</h1>
      <p>Description</p>
    </>
  );
}

2. Close All Tags

In JSX, all tags must be closed, including self-closing ones:

// ✅ Self-closing tags
<img src="photo.jpg" alt="A photo" />
<input type="text" />
<br />

3. Use camelCase for Attributes

HTML attributes become camelCase in JSX:

// HTML: class, onclick, tabindex
// JSX: className, onClick, tabIndex

<button className="btn" onClick={handleClick}>
  Click Me
</button>

JavaScript Expressions in JSX

Use curly braces {} to embed any JavaScript expression:

function Greeting({ name }) {
  const today = new Date().toLocaleDateString();

  return (
    <div>
      <h1>Hello, {name}!</h1>
      <p>Today is {today}</p>
      <p>2 + 2 = {2 + 2}</p>
    </div>
  );
}

Conditional Rendering

Using Ternary Operator

function Status({ isOnline }) {
  return (
    <span className={isOnline ? 'text-green' : 'text-gray'}>
      {isOnline ? 'Online' : 'Offline'}
    </span>
  );
}

Using && for Conditional Display

function Notification({ count }) {
  return (
    <div>
      {count > 0 && (
        <span className="badge">{count} new messages</span>
      )}
    </div>
  );
}

Rendering Lists

Use map() to render arrays. Always include a unique key prop:

function TodoList({ todos }) {
  return (
    <ul>
      {todos.map(todo => (
        <li key={todo.id}>
          {todo.text}
        </li>
      ))}
    </ul>
  );
}

The key helps React identify which items changed, were added, or removed. Use unique IDs when possible, not array indices.

Styling in JSX

Inline Styles (as Objects)

const buttonStyle = {
  backgroundColor: 'blue',
  color: 'white',
  padding: '10px 20px',
  borderRadius: '4px'
};

<button style={buttonStyle}>Styled Button</button>

CSS Classes

import './Button.css';

<button className="btn btn-primary">Click Me</button>

Key Takeaways

  • JSX is a syntax extension that looks like HTML but compiles to JavaScript
  • Always return a single root element (use Fragments when needed)
  • Use {} to embed JavaScript expressions
  • Use className instead of class, onClick instead of onclick
  • Always provide unique key props when rendering lists

Next, we'll learn how to build reusable components - the heart of React applications.

🧠 Quick Quiz

Test your understanding of this lesson.

1

What does JSX stand for?

2

In JSX, what attribute do you use instead of 'class' for CSS classes?

3

How do you embed a JavaScript expression in JSX?

Introduction to React