Skip
Arish's avatar

3. Understanding JSX


Understanding JSX

JSX (JavaScript XML) is a syntax extension for JavaScript that lets you write HTML-like code in your JavaScript files. It's not required in React, but it makes writing UI code much more intuitive.

What is JSX?

JSX looks like HTML but it's actually JavaScript:

jsx
1// This JSX
2const element = <h1 className="greeting">Hello, World!</h1>
3
4// Gets transformed to this JavaScript
5const element = React.createElement(
6  'h1',
7  { className: 'greeting' },
8  'Hello, World!'
9)

JSX Rules

1. Return a Single Root Element

JSX must have one parent element:

jsx
1// ❌ Wrong - multiple root elements
2function App() {
3  return (
4    <h1>Title</h1>
5    <p>Content</p>
6  )
7}
8
9// ✅ Correct - wrapped in a div
10function App() {
11  return (
12    <div>
13      <h1>Title</h1>
14      <p>Content</p>
15    </div>
16  )
17}
18
19// ✅ Better - use Fragment to avoid extra DOM element
20function App() {
21  return (
22    <>
23      <h1>Title</h1>
24      <p>Content</p>
25    </>
26  )
27}

2. Close All Tags

All tags must be closed, including self-closing tags:

jsx
1// ❌ Wrong
2<img src="photo.jpg">
3<input type="text">
4<br>
5
6// ✅ Correct
7<img src="photo.jpg" />
8<input type="text" />
9<br />

3. camelCase for Attributes

HTML attributes use camelCase in JSX:

jsx
1// HTML
2<div class="container" onclick="handleClick()">
3  <label for="name">Name</label>
4  <input type="text" tabindex="1">
5</div>
6
7// JSX
8<div className="container" onClick={handleClick}>
9  <label htmlFor="name">Name</label>
10  <input type="text" tabIndex={1} />
11</div>

Common attribute conversions:

  • classclassName
  • forhtmlFor
  • onclickonClick
  • tabindextabIndex
  • readonlyreadOnly

Embedding JavaScript in JSX

Use curly braces {} to embed JavaScript expressions:

Variables

jsx
1const name = 'John'
2const age = 25
3
4function Profile() {
5  return (
6    <div>
7      <h1>{name}</h1>
8      <p>Age: {age}</p>
9      <p>Next year: {age + 1}</p>
10    </div>
11  )
12}

Function Calls

jsx
1function formatName(user) {
2  return `${user.firstName} ${user.lastName}`
3}
4
5const user = { firstName: 'John', lastName: 'Doe' }
6
7function Greeting() {
8  return <h1>Hello, {formatName(user)}!</h1>
9}

Object Properties

jsx
1const product = {
2  name: 'iPhone',
3  price: 999,
4  inStock: true
5}
6
7function Product() {
8  return (
9    <div>
10      <h2>{product.name}</h2>
11      <p>${product.price}</p>
12      <span>{product.inStock ? 'In Stock' : 'Out of Stock'}</span>
13    </div>
14  )
15}

Ternary Operators

jsx
1function Greeting({ isLoggedIn }) {
2  return (
3    <div>
4      {isLoggedIn ? (
5        <h1>Welcome back!</h1>
6      ) : (
7        <h1>Please sign in</h1>
8      )}
9    </div>
10  )
11}

Logical AND (&&)

jsx
1function Notifications({ count }) {
2  return (
3    <div>
4      {count > 0 && (
5        <span className="badge">{count} new messages</span>
6      )}
7    </div>
8  )
9}

Styling in JSX

Inline Styles

Inline styles use an object with camelCase properties:

jsx
1// Inline style object
2const styles = {
3  backgroundColor: 'blue',
4  color: 'white',
5  padding: '10px 20px',
6  borderRadius: '5px'
7}
8
9function Button() {
10  return <button style={styles}>Click me</button>
11}
12
13// Or inline
14function Button() {
15  return (
16    <button style={{ backgroundColor: 'blue', color: 'white' }}>
17      Click me
18    </button>
19  )
20}

CSS Classes

jsx
1import './Button.css'
2
3function Button({ variant }) {
4  return (
5    <button className={`btn btn-${variant}`}>
6      Click me
7    </button>
8  )
9}
10
11// Dynamic classes
12function Button({ isActive }) {
13  return (
14    <button className={`btn ${isActive ? 'active' : ''}`}>
15      Click me
16    </button>
17  )
18}

Lists in JSX

Render lists using map():

jsx
1const fruits = ['Apple', 'Banana', 'Cherry']
2
3function FruitList() {
4  return (
5    <ul>
6      {fruits.map((fruit, index) => (
7        <li key={index}>{fruit}</li>
8      ))}
9    </ul>
10  )
11}
12
13// With objects
14const users = [
15  { id: 1, name: 'John' },
16  { id: 2, name: 'Jane' },
17  { id: 3, name: 'Bob' }
18]
19
20function UserList() {
21  return (
22    <ul>
23      {users.map(user => (
24        <li key={user.id}>{user.name}</li>
25      ))}
26    </ul>
27  )
28}

Comments in JSX

jsx
1function App() {
2  return (
3    <div>
4      {/* This is a JSX comment */}
5      <h1>Hello</h1>
6      
7      {/* 
8        Multi-line
9        comment 
10      */}
11      <p>World</p>
12    </div>
13  )
14}

JSX Prevents Injection Attacks

React automatically escapes values embedded in JSX:

jsx
1const userInput = '<script>alert("hacked!")</script>'
2
3// This is safe - the script won't execute
4function Display() {
5  return <div>{userInput}</div>
6}
7// Renders as text: <script>alert("hacked!")</script>

JSX is Just JavaScript

Remember, JSX compiles to React.createElement() calls:

jsx
1// You can use JSX anywhere you use JavaScript
2const element = <h1>Hello</h1>
3
4// In arrays
5const elements = [
6  <li key="1">First</li>,
7  <li key="2">Second</li>
8]
9
10// In conditionals
11const content = isLoading ? <Spinner /> : <Data />
12
13// As function returns
14const getGreeting = (name) => <h1>Hello, {name}!</h1>

JSX makes your React code more readable and maintainable!