What is JSX?

Subject: React

What is JSX?

JSX (JavaScript XML) is a syntax extension for JavaScript that allows you to write HTML-like code inside JavaScript. It’s used in React to describe what the UI should look like.

Although browsers don’t understand JSX directly, tools like Babel compile it into regular JavaScript.

βœ… Example:

This gets compiled to:

➑️ Check JSX Cheat Sheet (React Syntax)


πŸ” Why Use JSX?

  • Declarative: Write UI in a way that’s easy to read and understand.
  • Compositional: Can nest and reuse components easily.
  • Integrated: Combines HTML + JavaScript logic seamlessly.

➑️ Check JSX Cheat Sheet (React Syntax)


🧱 JSX Syntax Basics

1. Single Root Element Required

A JSX expression must have one parent element.

❌ Invalid:

βœ… Valid:

2. Use className Instead of class

3. Use camelCase for HTML Attributes

4. Expressions inside {}

Can include:

  • Variables
  • Function calls
  • Operators
  • Ternary expressions

5. Self-Closing Tags

6. Style in JSX

➑️ Check JSX Cheat Sheet (React Syntax)


🧠 JSX Advanced Concepts

1. Conditional Rendering

πŸ”Ή Ternary:

πŸ”Ή Logical &&:

2. Lists & Keys

3. Fragments

4. JSX Inside Functions & Variables

➑️ Check JSX Cheat Sheet (React Syntax)


⚠️ Common JSX Errors

ErrorFix
Missing parent elementWrap with a <div> or <>
class instead of classNameAlways use className
Inline style syntaxUse camelCase and JS object
Forgot to close tagUse /> for self-closing tags

➑️ Check JSX Cheat Sheet (React Syntax)


πŸ“Œ JSX Summary

FeatureExample
HTML + JS Mix<h1>Hello, {name}</h1>
Stylingstyle={{ color: 'red' }}
Conditionals{isLoggedIn ? <Welcome /> : <Login />}
Lists{items.map(item => <li>{item}</li>)}
One Root ElementAlways wrap elements in a single parent

➑️ Check JSX Cheat Sheet (React Syntax)


πŸ”š Final Thoughts

JSX is not required, but it's highly recommended in React β€” it makes your code:

  • Easier to write
  • Easier to debug
  • Closer to how HTML works

➑️ Check JSX Cheat Sheet (React Syntax)