JSX

JavaScript XML - a syntax extension for JavaScript that allows you to write HTML-like code within JavaScript, commonly used with React.

Overview

JSX makes it easier to write and add HTML in React. It allows you to write markup that looks like HTML directly in your JavaScript code. Under the hood, JSX is transformed into regular JavaScript function calls. While not required for React, JSX makes code more readable and easier to write.

Example

javascript
// JSX syntax
function Welcome({ name }) {
  return (
    <div className="container">
      <h1>Hello, {name}!</h1>
      <p>Welcome to our site</p>
    </div>
  );
}

// Compiles to:
function Welcome({ name }) {
  return React.createElement(
    'div',
    { className: 'container' },
    React.createElement('h1', null, `Hello, ${name}!`),
    React.createElement('p', null, 'Welcome to our site')
  );
}

// Conditional rendering in JSX
function Message({ isLoggedIn }) {
  return (
    <div>
      {isLoggedIn ? (
        <p>Welcome back!</p>
      ) : (
        <p>Please log in</p>
      )}
    </div>
  );
}

Key Points

  • Looks like HTML but is JavaScript
  • Must return a single parent element
  • Use className instead of class
  • Embed JavaScript with curly braces
  • Self-closing tags must end with />

Learn More