← Back to Chapters

JSX Syntax & Rules

⚛️ JSX Syntax & Rules

? Quick Overview

JSX (JavaScript XML) lets you write HTML-like syntax directly inside JavaScript. It is not plain HTML — it is syntactic sugar for JavaScript function calls that return React elements. JSX makes your UI code more readable and expressive while still compiling down to regular JavaScript.

Each JSX expression is transformed into a call like React.createElement(). React then uses these elements to build and update the UI efficiently inside a target DOM node (usually a <div id="root">).

? Key Concepts in JSX

  • Every JSX snippet must have a single root element (one parent wrapping everything).
  • All JSX tags must be properly closed, including self-closing tags like <br /> and <img />.
  • Attributes use camelCase names such as className and htmlFor.
  • You can embed JavaScript expressions inside braces { } for dynamic values.
  • JSX supports expressions (variables, function calls, operators) but not statements like if or for directly.
  • Inline styles are passed as a JavaScript object, not as a string.

? JSX Syntax & Theory

When you write JSX, you are writing a more readable layer on top of React's element creation API. The JSX compiler checks the structure of your tags and transforms them into nested JavaScript objects that describe your UI.

  • Single Parent Element: Wrap multiple elements in a single parent like <div> or <>...</> (React Fragment).
  • Proper Tag Closure: All tags must be closed to avoid syntax errors and unexpected rendering issues.
  • CamelCase Attributes: DOM attributes like onclick and tabindex become onClick and tabIndex in JSX.
  • JavaScript in Braces: Use { } to insert variables, function results, and simple calculations directly into your markup.
  • Expressions Only: Control flow (e.g., if / for) must live in JavaScript, not directly in JSX markup.

? Basic JSX Example

This example creates a simple React element and renders it into a DOM container using ReactDOM.

? View Code Example
// Render a simple heading inside the root div
const element = <h1>Welcome to React!</h1>;
const container = ReactDOM.createRoot(document.getElementById("root"));
container.render(element);

? Live Output / Explanation

React creates an element that represents <h1>Welcome to React!</h1> and mounts it into the DOM node with ID root. On the page, you will see a big heading saying "Welcome to React!".

? Dynamic JSX with JavaScript Expressions

JSX becomes powerful when you inject JavaScript values into your UI using curly braces. The values are evaluated at render time.

? View Code Example
// Inject dynamic values into JSX using curly braces
const user = "Aarav";
const time = new Date().toLocaleTimeString();

const element = (
<div>
<h2>Hello, {user}!</h2>
<p>Current time: {time}</p>
</div>
);

? Live Output / Explanation

When rendered, this JSX produces a <div> containing a personalized greeting and the current time, for example:

Hello, Aarav!
Current time: 4:15:32 PM

Any time the component re-renders, the expressions inside { } are re-evaluated so the UI always reflects the latest values.

? Styling & Attributes in JSX

JSX lets you apply classes and styles similar to HTML, but in a JavaScript-friendly way. CSS classes use className and inline styles are JavaScript objects.

? View Code Example
// Apply a style object and className in JSX
const style = { color: "blue", fontSize: "20px" };

const element = <h1 style={style} className="heading">
Styled JSX Example
</h1>;

? Live Output / Explanation

This code creates an <h1> element with blue text and a font size of 20px. The className="heading" can be targeted in your CSS file, while the style object gives you quick inline customization using JavaScript.

⚠️ JSX Gotchas to Avoid

  • ❌ Returning multiple sibling elements without wrapping them in a single parent or React Fragment.
  • ❌ Using class instead of className for CSS classes.
  • ❌ Forgetting to close self-closing tags like <img /> or <br />.
  • ❌ Placing control statements (e.g., if, for) directly inside JSX markup.

? Tips & Best Practices

  • Use React Fragments <>...</> to group elements without adding extra nodes to the DOM.
  • Keep JSX readable by splitting long structures across multiple lines and using meaningful indentation (in your editor view).
  • Remember that JSX compiles to React.createElement() calls — the final result must always be valid JavaScript.
  • Wrap multi-line JSX in parentheses to avoid automatic semicolon insertion issues.
  • Extract repeated JSX into reusable components and functions to keep your files clean.
  • Prefer clear, descriptive names for props and variables to make JSX self-documenting.

? Try It Yourself / Practice

  1. Create a React component named ProfileCard that displays your name, age, and city using JSX.
  2. Add inline styles to make the text blue and bold using a JavaScript style object.
  3. Use curly braces { } to insert a JavaScript variable like currentYear into your JSX.
  4. Ensure your JSX follows all syntax rules: a single root element, closed tags, and camelCase attributes.

Goal: Practice writing valid JSX, embedding JavaScript expressions, and applying attributes and styles while avoiding common JSX pitfalls.