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.
React.createElement()
{}
array.map() and
the key prop
<></> and
<React.Fragment>
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.
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:
@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:
// 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 WelcomeCardKey observations from this component:
()
after return. Without them, JS auto-inserts a
semicolon after return and your component
returns undefined.{} is a
JavaScript expression — variables, function calls, ternaries, template literals,
arithmetic.<img />, <input />, <br />. HTML allows leaving them open; JSX
does not.{/* comment */}. The // comment syntax only works outside the JSX
return block.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.
return ( <h1>Title</h1> <p>Paragraph</p> // ❌ Adjacent JSX elements // must be wrapped in enclosing tag )
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.
<img src="photo.jpg"> ← must self-close <input type="text"> ← must self-close <br> ← must self-close
<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.
<div class="card"></div> <label for="email"></label> <input tabindex="0" /> <div onclick={fn}></div>
<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).
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>
)
}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.
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 ✅ |
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>
)
}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.
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:
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>
)
}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:
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.
// 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 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):
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.
// ✅ 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>
):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:
const count = 0 {count && <p>Items: {count}</p>} // Renders "0" on screen — falsy number // is rendered, not ignored!
const count = 0 {count > 0 && <p>Items: {count}</p>} // count > 0 is false → nothing rendered // always use explicit boolean comparisons
// Invokes immediately on every render <button onClick={handleClick()}> Click Me </button> // handleClick() runs at render time! // not on click!
// Passes reference — called on click <button onClick={handleClick}> Click Me </button> // No () — pass the function, // don't invoke it
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
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)}
Explore More Tutorials
Strengthen your React foundation with these related tutorials:
className instead of
class?
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).
{}.
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.
key
prop?
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.
count = 0?{count && <p>Items: {count}</p>}
<Fragment key={id}> instead of
the shorthand <></>?<button onClick={handleClick()}>Click</button>?
- 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 likeiforfor. - Key attribute differences:
className,htmlFor,onClick,tabIndex,style={{}}. - Conditionals: use
&&for show/hide, ternary for A/B, or moveif/elseabove the return. - List rendering:
array.map()+ a stable uniquekeyprop on every item — never use index for mutable lists. - Fragments (
<></>) group elements without adding DOM nodes. Use<Fragment key={}›insidemap(). - Inline
styleuses 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
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.