JSX Fundamentals
Understanding JSX syntax and how it combines HTML with JavaScript
What is JSX?
JSX (JavaScript XML) is a syntax extension for JavaScript that looks like HTML. It allows you to write UI code that's intuitive and readable. JSX is not valid JavaScript—it gets transformed into regular JavaScript function calls by a compiler like Babel.
JSX vs HTML
JSX looks like HTML but has some key differences. It's actually closer to JavaScript, which means you can embed expressions and use JavaScript logic directly in your markup.
Basic JSX Syntax
// JSX element
const element = <h1>Hello, World!</h1>;
// JSX with multiple elements (must have one parent)
const card = (
<div>
<h2>Card Title</h2>
<p>Card content goes here.</p>
</div>
);
// Using a fragment to avoid extra wrapper
const list = (
<>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</>
);
Embedding JavaScript Expressions
Use curly braces {} to embed any JavaScript expression in JSX:
const name = "Alice";
const age = 25;
function Greeting() {
return (
<div>
<h1>Hello, {name}!</h1>
<p>You are {age} years old.</p>
<p>Next year you'll be {age + 1}.</p>
<p>Current time: {new Date().toLocaleTimeString()}</p>
</div>
);
}
JSX Differences from HTML
| HTML | JSX | Reason |
|---|---|---|
class |
className |
class is reserved in JS |
for |
htmlFor |
for is reserved in JS |
onclick |
onClick |
camelCase for events |
tabindex |
tabIndex |
camelCase for attributes |
style="color: red" |
style={{color: 'red'}} |
Object instead of string |
Styling with className and style
function StyledComponent() {
const dynamicColor = "blue";
return (
<div>
{/* Using className for CSS classes */}
<h1 className="title primary-heading">
Styled Heading
</h1>
{/* Using inline styles (object syntax) */}
<p style={{
color: dynamicColor,
fontSize: '18px',
marginTop: '1rem',
backgroundColor: '#f0f0f0'
}}>
Inline styled paragraph
</p>
{/* Combining both */}
<button
className="btn btn-primary"
style={{ padding: '10px 20px' }}
>
Click Me
</button>
</div>
);
}
Conditional Rendering
function UserGreeting({ isLoggedIn, username }) {
return (
<div>
{/* Using ternary operator */}
{isLoggedIn ? (
<h1>Welcome back, {username}!</h1>
) : (
<h1>Please log in</h1>
)}
{/* Using && for conditional display */}
{isLoggedIn && (
<button>Log Out</button>
)}
{/* Conditional className */}
<div className={`status ${isLoggedIn ? 'online' : 'offline'}`}>
Status: {isLoggedIn ? 'Online' : 'Offline'}
</div>
</div>
);
}
Rendering Lists
function TodoList() {
const todos = [
{ id: 1, text: 'Learn React', done: true },
{ id: 2, text: 'Build a project', done: false },
{ id: 3, text: 'Deploy to production', done: false },
];
return (
<ul>
{todos.map(todo => (
<li
key={todo.id}
style={{
textDecoration: todo.done ? 'line-through' : 'none'
}}
>
{todo.text}
</li>
))}
</ul>
);
}
⚠️ Important: The key Prop
When rendering lists, always provide a unique key prop to each element. This helps React identify which items have changed, been added, or removed.
JSX Expressions vs Statements
✓ Expressions (Allowed)
- • Variables:
{name} - • Math:
{2 + 2} - • Ternary:
{x ? 'yes' : 'no'} - • Function calls:
{getData()} - • Array methods:
{arr.map(...)}
✗ Statements (Not Allowed)
- • if/else blocks
- • for/while loops
- • switch statements
- • Variable declarations
- • Function definitions
Self-Closing Tags
// All tags must be closed in JSX
// Self-closing tags
<img src="photo.jpg" alt="A photo" />
<input type="text" placeholder="Enter name" />
<br />
<hr />
// Custom components can also self-close
<MyComponent />
<Button />
Comments in JSX
function MyComponent() {
return (
<div>
{/* This is a JSX comment */}
<h1>Hello</h1>
{/*
Multi-line comments
work like this
*/}
<p>World</p>
</div>
);
}
🎯 JSX Best Practices
- ✓ Use parentheses around multi-line JSX for clarity
- ✓ Keep components small and focused
- ✓ Use fragments
<>...</>to avoid unnecessary wrapper divs - ✓ Always include the
keyprop when mapping arrays - ✓ Use meaningful variable names in expressions
- ✓ Extract complex logic outside the return statement