Tutorials React JS JSX Basics
Ch 4 / 46
Chapter 4 Beginner 12 min read React JS

JSX Basics

JSX — JavaScript XML — is the syntax extension that lets you write HTML-like markup directly inside JavaScript. It's the heart of every React component. In this chapter you'll master all the JSX rules, learn how to embed JavaScript expressions, understand the differences between JSX and HTML attributes, use conditional rendering, render lists with map(), wrap elements in Fragments, and avoid the most common JSX pitfalls that trip up beginners.

Advertisement
What you'll learn
What is JSX — how Babel transforms it to React.createElement()
JSX syntax rules — one root, self-closing, camelCase, className
JavaScript expressions — embedding variables, functions, ternaries in {}
JSX vs HTML attributes — className, htmlFor, style, onClick and more
Conditional rendering — &&, ternary, if/else and switch patterns
List rendering — array.map() and the key prop
Fragments — <></> and <React.Fragment>
Inline styles — double curly brace syntax and the style object

1. What is JSX?

JSX stands for JavaScript XML. It's a syntax extension for JavaScript that looks like HTML but lives inside your .jsx / .tsx files. JSX is not valid JavaScript by itself — a transpiler like Babel (or the SWC compiler in Vite) transforms it into standard React.createElement() calls before it reaches the browser.

JSX is optional — but universal You can write React without JSX using raw React.createElement() calls. But every React developer uses JSX because it's dramatically more readable. You'll almost never see raw createElement in real code.

This is what Babel does to your JSX under the hood:

You write (JSX)
function App() { return ( <h1 className="title"> Hello World </h1> ) }
→
Babel transforms to
function App() { return React.createElement( "h1", { className: "title" }, "Hello World" ) }
→
Browser renders
<h1 class="title"> Hello World </h1> // Real DOM node // visible in the browser
New JSX Transform (React 17+) Since React 17, you no longer need to import React at the top of every file. The new JSX transform automatically imports the necessary functions. Vite's @vitejs/plugin-react uses this new transform by default. Older code you'll find online may still have import React from 'react' at the top — that's fine but no longer required.

2. How JSX Works — Your First Component

Let's write a complete, working React component using JSX and understand exactly what's happening at each line:

jsx — src/components/WelcomeCard.jsx
// No "import React from 'react'" needed — Vite uses new JSX transform function WelcomeCard() { // Regular JavaScript variables const name = "Arjun" const year = new Date().getFullYear() const isAdmin = true // JSX — returned like HTML, but it's JavaScript return ( <div className="card"> <h2>Welcome, {name}!</h2> {/* expression */} <p>Year: {year}</p> {/* expression */} <p>Role: {isAdmin ? "Admin" : "User"}</p> {/* ternary */} <img src="/avatar.png" alt="Avatar" /> {/* self-closing */} </div> ) } export default WelcomeCard

Key observations from this component:

Parentheses for multi-line
Wrap multi-line JSX in () after return. Without them, JS auto-inserts a semicolon after return and your component returns undefined.
Curly braces = JS
Anything inside {} is a JavaScript expression — variables, function calls, ternaries, template literals, arithmetic.
Self-closing tags
Tags with no children must be self-closed in JSX: <img />, <input />, <br />. HTML allows leaving them open; JSX does not.
Comments in JSX
Comments inside JSX markup must use {/* comment */}. The // comment syntax only works outside the JSX return block.
Advertisement

3. The Core JSX Rules You Must Know

JSX has a small set of strict rules. Break any one of them and React will throw an error. Learn these once and they become second nature:

Rule 1 — Return a Single Root Element

Every component must return one root element. You cannot return two sibling elements side-by-side — wrap them in a parent <div> or a Fragment.

❌ Wrong — two roots
return (
    <h1>Title</h1>
    <p>Paragraph</p>
  // ❌ Adjacent JSX elements
  // must be wrapped in enclosing tag
)
✅ Correct — one root
return (
  <>
    <h1>Title</h1>
    <p>Paragraph</p>
  </>
  // ✅ Fragment wraps both
)

Rule 2 — Close All Tags

Every HTML element must be explicitly closed in JSX. Tags with no children use the self-closing /> syntax.

❌ Wrong — unclosed tags
<img src="photo.jpg">    ← must self-close
<input type="text">       ← must self-close
<br>                  ← must self-close
✅ Correct — all closed
<img src="photo.jpg" />   ← self-closed
<input type="text" />      ← self-closed
<br />                 ← self-closed

Rule 3 — Use camelCase for Most Attributes

JSX attribute names use camelCase because they map to JavaScript DOM properties, not HTML attributes.

❌ HTML syntax (wrong in JSX)
<div class="card"></div>
<label for="email"></label>
<input tabindex="0" />
<div onclick={fn}></div>
✅ JSX syntax (correct)
<div className="card"></div>
<label htmlFor="email"></label>
<input tabIndex="0" />
<div onClick={fn}></div>

4. Embedding JavaScript Expressions with {}

The most powerful feature of JSX is embedding live JavaScript inside your markup using curly braces {}. Any valid JavaScript expression can go between the curly braces — but not statements (no if/else, for, while directly inside JSX).

jsx — all the things you can embed with {}
function ExpressionsDemo() { const name = "Priya" const score = 87 const items = ["React", "Vite", "Tailwind"] const getGreeting = (n) => `Hello, ${n}!` return ( <div> {/* ── Variables ── */} <p>Name: {name}</p> {/* ── Arithmetic ── */} <p>Score + bonus: {score + 10}</p> {/* ── Template literal ── */} <p>{`Score is ${score}`}</p> {/* ── Function call ── */} <p>{getGreeting(name)}</p> {/* ── Ternary expression ── */} <p>{score >= 90 ? "Excellent" : "Good"}</p> {/* ── Array length ── */} <p>Tech count: {items.length}</p> {/* ── Array join ── */} <p>Stack: {items.join(" · ")}</p> {/* ── Object property ── */} <p>Current year: {new Date().getFullYear()}</p> </div> ) }
Expressions only — no statements You cannot use if, for, while, switch, or let/const declarations directly inside JSX curly braces. These are statements, not expressions. Use ternary operators or && for conditionals inside JSX, and move complex logic into variables above the return.
⭐⭐⭐⭐⭐
4.9 / 5
🔥 Most Popular at K2infocom · Vadodara
React JS Complete
Masterclass
Go from JSX basics to full-stack React apps. Hooks, State, Context, Router, Redux, API integration & 6 real-world projects — all in one course.
JSX & Components Hooks & State React Router Redux Toolkit REST APIs 6 Projects
2,500+Students
6+Projects
3–6Months
100%Placement

5. JSX Attributes vs HTML Attributes

JSX attributes closely mirror HTML but with important differences. The most common trip-up for beginners: class becomes className, and for becomes htmlFor, because class and for are reserved words in JavaScript.

HTML Attribute JSX Equivalent Example Notes
class className <div className="card"> class is reserved in JS
for htmlFor <label htmlFor="email"> for is reserved in JS
onclick onClick <button onClick={fn}> camelCase event handlers
onchange onChange <input onChange={fn}> camelCase
tabindex tabIndex <div tabIndex={0}> camelCase
style="color:red" style={{ color:'red' }} <p style={{ color:'red' }}> object, not string
stroke-width strokeWidth SVG attributes Hyphenated → camelCase
aria-label aria-label <button aria-label="Close"> ARIA stays hyphenated ✅
data-id data-id <div data-id="42"> data-* stays hyphenated ✅
jsx — JSX attribute examples in a form
function LoginForm() { const handleSubmit = (e) => { e.preventDefault() console.log('Submitted!') } return ( <form className="form" onSubmit={handleSubmit}> <label htmlFor="email">Email</label> <input id="email" type="email" className="input" placeholder="you@example.com" aria-label="Email address" tabIndex={1} autoFocus /> <button type="submit" className="btn"> Login </button> </form> ) }
Advertisement

6. Conditional Rendering in JSX

JSX can't use if/else statements inside {}, but you have four powerful patterns for conditionally showing or hiding elements:

// && — show element ONLY when condition is true
function Notification({ hasAlert }) {
  return (
    <div>
      <h2>Dashboard</h2>
      {hasAlert && <p className="alert">⚠️ New alert!</p>}
    </div>
  )
}
// <Notification hasAlert={true}  />  → shows the alert paragraph
// <Notification hasAlert={false} />  → renders nothing for that line

// ⚠️ Pitfall — avoid falsy numbers!
const count = 0
{count && <p>Items: {count}</p>}   // ❌ renders "0" in the browser!
{count > 0 && <p>Items: {count}</p>} // ✅ safe — explicit boolean check
// Ternary — show one thing OR another
function AuthButton({ isLoggedIn }) {
  return (
    <div>
      {isLoggedIn
        ? <button>Log Out</button>
        : <button>Log In</button>
      }
    </div>
  )
}

// Inline ternary for text/values
function Status({ score }) {
  return (
    <p>
      Grade: {score >= 90 ? "A" : score >= 70 ? "B" : "C"}
    </p>
  )
}
// Tip: for complex logic, move the ternary into a variable above return
// if/else — move logic ABOVE the return statement
function UserCard({ user }) {
  let content

  if (!user) {
    content = <p>Loading...</p>
  } else if (user.banned) {
    content = <p className="error">Account suspended</p>
  } else {
    content = <p>Welcome, {user.name}!</p>
  }

  return <div className="card">{content}</div>
}

// Or use early returns for guard clauses
function Profile({ user }) {
  if (!user) return <p>No user found</p>
  return <h1>{user.name}</h1>
}
// return null — render nothing at all
function Banner({ show }) {
  if (!show) return null   // component renders nothing
  return <div className="banner">🎉 Welcome Back!</div>
}

// Nullish coalescing — show fallback
function UserName({ name }) {
  return <p>{name ?? "Anonymous"}</p>
  // shows "Anonymous" if name is null or undefined
}

// Optional chaining in JSX
<p>{user?.profile?.bio ?? "No bio yet"}</p>

7. Rendering Lists with array.map()

To render a list of items in JSX, you use JavaScript's Array.map() method to transform an array of data into an array of JSX elements. React then renders all of them. The critical requirement: every list item must have a unique key prop.

jsx — basic list rendering with map()
const fruits = ["🍎 Apple", "🍌 Banana", "🍇 Grapes", "🥭 Mango"] function FruitList() { return ( <ul> {fruits.map((fruit, index) => ( <li key={index}>{fruit}</li> ))} </ul> ) }

A more realistic example with an array of objects — always prefer a stable unique ID over the index:

jsx — list of objects with id as key (best practice)
const products = [ { id: 1, name: "React Course", price: 1999 }, { id: 2, name: "Vite Starter", price: 499 }, { id: 3, name: "Tailwind Kit", price: 799 }, ] function ProductCard({ product }) { return ( <div className="card"> <h3>{product.name}</h3> <p>₹{product.price}</p> </div> ) } function ProductList() { return ( <div className="grid"> {products.map((product) => ( <ProductCard key={product.id} {/* ✅ stable unique ID as key */} product={product} /> ))} </div> ) }
The key Prop Rules Keys must be unique among siblings in the same list — not globally unique. React uses keys to know which items changed, added, or removed during re-renders.

Avoid using array index as key when items can be reordered, filtered, or deleted. Index keys can cause incorrect component state. Always prefer a stable database ID or UUID. Use the index only for static, unchanging lists.

You can chain .filter() before .map() to show only matching items:

jsx — filter + map pattern
function TaskList({ tasks }) { return ( <ul> {tasks .filter(task => !task.done) // show only incomplete tasks .map(task => ( <li key={task.id}>{task.title}</li> )) } </ul> ) }

8. React Fragments — Avoid Unnecessary Wrapper Divs

Every component must return one root element. The naive solution is wrapping everything in a <div> — but that adds an unnecessary DOM node that can break CSS layouts (like Flexbox or Grid children). Fragments are the solution: they let you group elements without adding any real DOM node.

❌ Extra <div> breaks layout
// Table rows inside a wrapper div
// → invalid HTML, breaks table
function TableRows() {
  return (
    <div>          ← extra DOM node!
      <tr><td>Row 1</td></tr>
      <tr><td>Row 2</td></tr>
    </div>
  )
}
✅ Fragment — no extra DOM
// Fragment — no extra DOM node
// → valid HTML structure
function TableRows() {
  return (
    <>            ← no DOM node added
      <tr><td>Row 1</td></tr>
      <tr><td>Row 2</td></tr>
    </>
  )
}

Three ways to use Fragments — all equivalent (except the key prop):

jsx — Fragment syntax options
import { Fragment } from 'react' // 1. Short syntax (most common) — no key prop support return ( <> <h1>Title</h1> <p>Paragraph</p> </> ) // 2. React.Fragment — also no key return ( <React.Fragment> <h1>Title</h1> <p>Paragraph</p> </React.Fragment> ) // 3. Named Fragment with key — needed inside map() {items.map(item => ( <Fragment key={item.id}> {/* <> can't take a key prop */} <dt>{item.term}</dt> <dd>{item.definition}</dd> </Fragment> ))}

9. Inline Styles — The Double Curly Brace Pattern

In HTML, style takes a string: style="color: red; font-size: 16px". In JSX, style takes a JavaScript object, and CSS property names become camelCase. The double curly braces are: outer {} = JSX expression, inner {} = object literal.

jsx — inline style patterns
// ✅ Inline — double curly braces <h1 style={{ color: '#61dafb', fontSize: '24px' }}> Hello React </h1> // ✅ Style object defined above return (cleaner) const cardStyle = { background: '#1e1e2e', padding: '20px', borderRadius: '12px', // camelCase! boxShadow: '0 4px 24px rgba(0,0,0,.4)', maxWidth: '400px', } return <div style={cardStyle}>Card content</div> // ✅ Dynamic values — combine static + dynamic const isActive = true return ( <div style={{ color: isActive ? '#22c55e' : '#ef4444', fontWeight: isActive ? 700 : 400, }} > Status </div> )
CSS Modules & Tailwind are better Inline styles don't support pseudo-classes (:hover), media queries, or animations. For real projects, use CSS Modules (App.module.css), Tailwind CSS utility classes, or styled-components. Inline styles are fine for truly dynamic values (e.g., a progress bar width calculated in JS).

10. Common JSX Pitfalls & How to Fix Them

These are the errors beginners hit most often. Recognise the pattern, know the fix:

❌ Rendering 0 with &&
const count = 0
{count && <p>Items: {count}</p>}
// Renders "0" on screen — falsy number
// is rendered, not ignored!
✅ Explicit boolean check
const count = 0
{count > 0 && <p>Items: {count}</p>}
// count > 0 is false → nothing rendered
// always use explicit boolean comparisons
❌ Calling function inside JSX
// Invokes immediately on every render
<button onClick={handleClick()}>
  Click Me
</button>
// handleClick() runs at render time!
// not on click!
✅ Pass function reference
// Passes reference — called on click
<button onClick={handleClick}>
  Click Me
</button>
// No () — pass the function,
// don't invoke it
❌ Objects as children
const user = { name: "Dev", age: 25 }
// ❌ Objects can't be rendered directly
return <p>{user}</p>
// Error: Objects are not valid as
// a React child
✅ Access specific properties
const user = { name: "Dev", age: 25 }
// ✅ Render specific string properties
return <p>{user.name} — Age: {user.age}</p>
// Or JSON.stringify() for debugging:
// {JSON.stringify(user)}
Practise JSX in Your Browser
Use OneCompiler's React playground to try every JSX pattern from this chapter — no setup, runs instantly.
Open React Playground
Advertisement
Quick Check — Test Your Understanding
Q1. Why does JSX use className instead of class?
✅ Answer
Because class is a reserved keyword in JavaScript (used to define classes with class MyComponent {}). JSX compiles to JavaScript, so it must avoid reserved words.

className maps directly to the DOM property element.className. Similarly, for (used in <label for>) becomes htmlFor because for is also reserved (used in for loops).
Q2. What is the difference between expressions and statements in JSX curly braces?
✅ Answer
An expression evaluates to a value — variables, arithmetic, function calls, ternaries, array methods. These work inside JSX {}.

A statement performs an action but doesn't produce a value — if/else, for, while, const x = 5. These cannot be placed directly inside JSX curly braces.

Solutions: use ternary (condition ? a : b) or && for conditionals inside JSX. Move complex logic into variables above the return statement.
Q3. Why should you avoid using the array index as a key prop?
✅ Answer
React uses key to efficiently reconcile the virtual DOM — it identifies which items changed, moved or were removed. When you use the array index as the key:
  • If you delete item at index 0, everything shifts — React thinks all items after it changed, causing unnecessary re-renders.
  • If items have internal state (like input values), that state gets mixed up because React associates it with the wrong component.
  • Sorting or filtering causes incorrect component reuse.
Use a stable, unique ID (database ID, UUID) as the key whenever items can be added, removed, or reordered. The index is safe only for static lists that never change.
Multiple Choice Questions
MCQ 1
Which of the following is valid JSX syntax for a self-closing input tag?
MCQ 2
What does the following JSX render when count = 0?
{count && <p>Items: {count}</p>}
MCQ 3
When do you use <Fragment key={id}> instead of the shorthand <></>?
MCQ 4
What is wrong with <button onClick={handleClick()}>Click</button>?
Chapter 4 Summary
  • JSX is a syntax extension — Babel transforms it to React.createElement() calls at build time.
  • Three core rules: single root element, close all tags, camelCase attributes.
  • Use {} to embed JavaScript expressions — not statements like if or for.
  • Key attribute differences: className, htmlFor, onClick, tabIndex, style={{}}.
  • Conditionals: use && for show/hide, ternary for A/B, or move if/else above the return.
  • List rendering: array.map() + a stable unique key prop on every item — never use index for mutable lists.
  • Fragments (<></>) group elements without adding DOM nodes. Use <Fragment key={}› inside map().
  • Inline style uses a JS object with camelCase property names, not a CSS string.
  • Common pitfalls: 0 && renders "0", onClick={fn()} calls immediately, objects can't be rendered directly.

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel