← Back to Chapters

JSX (JavaScript XML)

⚛️ JSX (JavaScript XML)

? Quick Overview

JSX (JavaScript XML) is a syntax extension for JavaScript used in React to describe what the UI should look like. It lets you write HTML-like code directly inside JavaScript, which is later compiled into React.createElement() calls by tools like Babel.

JSX makes React components more readable, declarative, and easier to maintain by combining markup and logic in a single place.

✅ JSX is not required, but highly recommended

? Key Concepts in JSX

  • HTML-like syntax inside JavaScript files.
  • Compiled to React.createElement() calls under the hood.
  • Supports JavaScript expressions inside { }.
  • Every JSX expression must have one parent element.
  • Uses camelCase attributes and className instead of class.

? JSX Syntax & Theory

JSX looks like HTML but follows JavaScript rules. When the code is built, Babel converts JSX into plain JavaScript objects using React.createElement(). React then uses these objects to build the Virtual DOM and update the UI efficiently.

  • JSX is written inside parentheses ( ) when returned from a function.
  • All tags must be properly closed (e.g., <img />, <br />).
  • Attributes use camelCase, e.g., onClick, tabIndex, className.

? Without JSX vs With JSX

Without JSX, you write React elements using React.createElement(). With JSX, the same UI looks much closer to HTML and is easier to understand.

? View Code Example
// Comparing React elements with and without JSX
const elementWithoutJSX = React.createElement("h1", null, "Hello, React!");

const elementWithJSX = <h1>Hello, React!</h1>;

console.log(elementWithoutJSX);
console.log(elementWithJSX);

?️ Output / Explanation

Both elementWithoutJSX and elementWithJSX represent the same virtual DOM structure: an <h1> element with the text "Hello, React!". JSX is just a more readable way to write the same thing.

? Embedding Expressions in JSX

You can embed JavaScript expressions inside JSX using curly braces { }. These expressions can be variables, function calls, or even calculations.

? View Code Example
// Using JavaScript values and functions inside JSX
const name = "Aarav";

const greetingElement = <h2>Hello, {name}!</h2>;

function getGreeting(user) {
  return <h3>Welcome back, {user}!</h3>;
}

const personalizedGreeting = getGreeting("Aarav");

? What React Renders

  • greetingElement becomes: <h2>Hello, Aarav!</h2>.
  • personalizedGreeting becomes: <h3>Welcome back, Aarav!</h3>.

React replaces {name} and {user} with their current values when rendering the component.

? Single Parent Element Rule

Every JSX expression must return exactly one parent element. If you need to return multiple elements, wrap them inside a <div> or a React fragment <>...</>.

? View Code Example
// ✅ Valid JSX with a single parent element
function App() {
  return (
    <div>
      <h1>Title</h1>
      <p>This is valid JSX.</p>
    </div>
  );
}

// ✅ Using a React Fragment instead of a <div>
function AppFragment() {
  return (
    <>
      <h1>Title</h1>
      <p>This is also valid JSX.</p>
    </>
  );
}

// ❌ This would cause an error (two root elements)
// function BrokenApp() {
//   return (
//     <h1>Title</h1>
//     <p>This is invalid JSX.</p>
//   );
// }

? JSX Attributes & Styling

JSX uses camelCase for attribute names and allows inline styles using JavaScript objects. Use className instead of class.

? View Code Example
// Styling JSX using className and inline styles
const headingStyle = {
  color: "blue",
  fontSize: "24px"
};

function StyledHeading() {
  return (
    <h1 className="title" style={headingStyle}>
      Styled Text
    </h1>
  );
}

?️ Output / Explanation

The component StyledHeading renders an <h1> element with the text "Styled Text", blue color, and font size of 24px. The CSS class title can also be used to apply extra styles from a stylesheet.

⚡ Why Use JSX?

  • ✅ Makes React code more readable and declarative.
  • ✅ Lets you mix UI markup and JavaScript logic in one place.
  • ✅ Catches many syntax errors at compile time using tools like Babel.
  • ✅ Works naturally with React components, props, and state updates.

? Tips & Best Practices for JSX

  • Always close all tags in JSX (e.g., <img />, <input />).
  • JSX is not a string — do not wrap it in quotes.
  • Wrap multiple elements inside a single parent element or a fragment.
  • Only expressions (not statements) are allowed inside { } in JSX.
  • Use meaningful component names starting with a capital letter (e.g., Greeting).

? Try It Yourself

  1. Create a new React component file named Greeting.js.
  2. Inside it, use JSX to display a message like Welcome, {`{name}`}! using a variable name.
  3. Apply inline styles to change the color and font size of the greeting text.
  4. Return multiple elements (like a heading and a paragraph) using a React fragment instead of a <div>.

Goal: Understand JSX syntax, how to embed JavaScript expressions, and how to apply styling and structure properly in React components.

? Sample Solution Idea
// Simple Greeting component using JSX
function Greeting() {
  const name = "Aarav";
  const style = {
    color: "purple",
    fontSize: "28px"
  };

  return (
    <>
      <h1 style={style}>Welcome, {name}!</h1>
      <p>This message is rendered using JSX.</p>
    </>
  );
}