Lesson 5 +10 XP

Core JSX Syntax Rules

Core JSX Syntax Rules

JSX is a markup extension with strict JavaScript-based structural rules. Understanding these syntax constraints is crucial to avoid syntax errors when writing React components.

Rule 1: Return a Single Root Element

Every JSX expression must return a single top-level element. If you have multiple sibling elements, they must be wrapped inside a parent element (such as a <div>, <article>, or Fragment).

// ❌ WRONG: Syntax Error (Multiple sibling elements without wrapper)
return (
  <h1>Header</h1>
  <p>Paragraph</p>
);

// ✅ CORRECT: Wrapped in a single parent element
return (
  <div>
    <h1>Header</h1>
    <p>Paragraph</p>
  </div>
);

Rule 2: Close All Elements Explicitly

In traditional HTML, elements like <img>, <input>, and <br> do not require closing tags. In JSX, all tags must be closed, either with a matching closing tag or a self-closing slash.

// ❌ WRONG: Unclosed tag
<img src="photo.jpg">

// ✅ CORRECT: Self-closing tag
<img src="photo.jpg" />

Rule 3: Use camelCase for Most Attributes

Because JSX is converted into JavaScript objects, properties are named using JavaScript camelCase conventions instead of lowercase HTML hyphenated names.

HTML AttributeJSX Equivalent
classclassName
tabindextabIndex
onclickonClick
autocompleteautoComplete
aria- / data-Kept as hyphenated (aria-label, data-id)
// Correct camelCase attribute usage
<button className="primary-btn" onClick={handleClick} tabIndex={1}>
  Click Me
</button>

Summary & TL;DR

  • A JSX block must return exactly one single root element.
  • All tags in JSX must be explicitly closed (e.g. <br />, <input />).
  • Use camelCase for standard attributes (className, onClick), except for aria- and data- attributes.