Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

React FAQ: Top 75 Questions

3. What is JSX in React?

JSX (JavaScript XML) is a syntax extension for JavaScript recommended by React to describe what the UI should look like. It allows you to write HTML-like code directly within your JavaScript files, making it easier to visualize the UI structure alongside the logic that renders it.

Key points about JSX:

  • Not HTML or a String: JSX is not a plain string or HTML; it's a syntax sugar for `React.createElement()` calls. Behind the scenes, a transpiler like Babel converts JSX code into standard JavaScript function calls that create React elements.
  • Closer to JavaScript: While it looks like HTML, JSX is actually closer to JavaScript. You can embed JavaScript expressions within JSX by wrapping them in curly braces `{}`.
  • Self-Closing Tags: In JSX, if an element has no children, you must close it with `/>` (e.g., ` ` or ` `).
  • CamelCase for Attributes: HTML attributes like `class` become `className`, and `for` becomes `htmlFor` in JSX, following JavaScript's camelCase convention.
  • Fragments (`<>` or ` `): React components must return a single root element. If you need to return multiple elements without adding an extra DOM node, you can wrap them in a Fragment.

JSX makes your React code more readable, understandable, and provides a clear separation of concerns by coupling rendering logic with UI markup.


import React from 'react';
import ReactDOM from 'react-dom/client';

const name = "Alice";
const isLoggedIn = true;

// Basic JSX element
const welcomeElement = <h1>Hello, world!</h1>;

// Embedding JavaScript expressions
const greetingElement = <p>Welcome, {name}!</p>;

// Using conditional rendering with JSX
function UserGreeting(props) {
  if (props.isLoggedIn) {
    return <h2>Welcome back!</h2>;
  }
  return <h2>Please sign up.</h2>;
}

// Combining multiple elements with a Fragment
function App() {
  const items = ['Apple', 'Banana', 'Cherry'];
  return (
    <> {/* This is a React Fragment */}
      {welcomeElement}
      {greetingElement}
      <UserGreeting isLoggedIn={isLoggedIn} />

      <ul className="my-list"> {/* className instead of class */}
        {items.map((item, index) => (
          <li key={index}>{item}</li> // Using key for list items
        ))}
      </ul>

      <input type="text" placeholder="Enter text" /> {/* Self-closing tag */}
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root-jsx'));
root.render(<App />);
                    

Explanation of the Code:

  • `welcomeElement` shows the simplest form of JSX, looking exactly like HTML.
  • `greetingElement` demonstrates embedding a JavaScript variable (`name`) directly into JSX using curly braces `{}`.
  • `UserGreeting` illustrates **conditional rendering** within JSX; different JSX is returned based on the `isLoggedIn` prop.
  • In the `App` component:
    • The use of `<>` and `` is a shorthand for `React.Fragment`, allowing multiple top-level elements to be returned without adding an unnecessary `div` to the DOM.
    • `className` is used instead of `class` for CSS classes, as `class` is a reserved keyword in JavaScript.
    • The `map` function is used inside JSX to render a list of `li` elements, showing how to iterate and render dynamic content. Each list item requires a unique `key` prop for efficient updates by React.
    • ` ` demonstrates a **self-closing tag**, mandatory in JSX for elements without children.

JSX makes the code declarative and visually intuitive, allowing developers to define UI structure directly alongside their component logic.