JSX in React
Table of Contents + −
In the previous lesson, we created our first React application and noticed that React component files use .jsx
extension. In this lesson, we’ll learn what JSX is and how it works.
What is JSX?
JSX stands for JavaScript XML. It is a syntax extension for JavaScript that allows you to write HTML-like code directly inside your JavaScript files.
Here’s a simple example:
const element = <h1>Hello, World!</h1>;
This looks like we are assigning an HTML element to a JavaScript variable, but it’s actually a special syntax that can only be used inside React components. Behind the scenes, React converts this JSX into pure JavaScript code that creates actual DOM elements that a browser can understand.
💡 Fun Fact
JSX was created by Facebook (now Meta) to make React development more intuitive for developers who already knew HTML!
How JSX Works Behind the Scenes
When you write JSX, it gets converted into React.createElement()
function calls. For Example, the JSX code:
JSX Code:
const element = <h1>Hello, World!</h1>;
JSX to HTML:
const element = React.createElement('h1', null, 'Hello, World!');
Multiple HTML Elements in JSX:
Similarly, if we use multiple HTML elements in JSX, as below:
const element = ( <div className="greeting"> <h1>Hello, World!</h1> <p>Welcome to React!</p> </div>);
Behind the scenes, this gets converted to multiple React.createElement()
calls as below:
const element = React.createElement( 'div', { className: 'greeting' }, React.createElement('h1', null, 'Hello, World!'), React.createElement('p', null, 'Welcome to React!'));
As you can see, instead of we call React.createElement()
directly, React helps us by making us write HTML-like code i.e. JSX, which is much more readable and easier to write than using React.createElement()
directly.
🎉 Isn't it Amazing?
JSX transforms complex JavaScript function calls into beautiful, readable HTML-like syntax that any web developer can understand at first glance!
React.createElement()
The React.createElement()
method is what actually converts JSX into HTML elements that browser can easily render. Let’s see how it works.
🔍 Behind the Scenes
Think of React.createElement()
as React’s magic translator that converts your JSX into language the browser understands!
React.createElement() Syntax:
React.createElement(type, props, ...children)
As you can see, React.createElement()
method takes three arguments:
Parameters:
-
type: The type of element to create. This can be:
- A string for HTML tags:
'div'
,'h1'
,'p'
, etc. - A React component - a function or class that returns JSX.
- A string for HTML tags:
-
props: A javascript object containing the properties/attributes for the element. If there are no props, it’s
null
. -
children: The content inside the element. It can be text, other elements or React components. You can pass multiple children by separating them with commas.
JSX vs createElement Examples:
We will now look at some examples to see how JSX gets converted to React.createElement()
calls.
- Simple JSX Element: If we want to create a simple button with a onClick handler and a class name, we can write it in JSX like this:
<button className="btn" onClick={handleClick}> Click me</button>
And the above JSX code gets converted to:
React.createElement( 'button', { className: 'btn', onClick: handleClick }, 'Click me');
- JSX with Nested Elements: If we want to create a card with a title and description, we can write it in JSX like this:
<div className="card"> <h2>Card Title</h2> <p>Card description</p></div>
And the above JSX code gets converted to:
React.createElement( 'div', { className: 'card' }, React.createElement('h2', null, 'Card Title'), React.createElement('p', null, 'Card description'));
As you can see, JSX is much more readable and easier to write than using React.createElement()
directly!
💭 Think About It
Imagine writing an entire website using only React.createElement()
calls - it would be like writing a novel using only technical manuals! JSX brings back the simplicity and beauty of HTML.
Basic JSX Rules
JSX looks like HTML, but it has some important rules you need to follow:
1. All Tags Must Be Closed
In HTML, some tags don’t need to be closed, but in JSX, every tag must be closed:
✅ Correct JSX
<img src="image.jpg" alt="Description" /><input type="text" /><br /><div></div>
❌ Wrong - This won’t work in JSX
<img src="image.jpg" alt="Description"><input type="text"><br><div>
2. Use className Instead of class
Since class
is a reserved word in JavaScript, JSX uses className
:
// ✅ Correct<div className="container">Content</div>
// ❌ Wrong - 'class' is reserved in JavaScript<div class="container">Content</div>
3. Must Have One Parent Element
JSX must return a single parent element:
❌ Wrong - Multiple elements at the same level
function MyComponent() { return ( <h1>Title</h1> <p>Paragraph</p> );}
✅ Correct - Wrapped in a single parent
function MyComponent() { return ( <div> <h1>Title</h1> <p>Paragraph</p> </div> );}
Does JSX actually gets converted to HTML elements?
Yes, JSX is syntactic sugar for React.createElement()
calls, which create virtual DOM elements that React uses to create actual HTML elements in the browser. Next we will learn about Virtual DOM and how React updates the UI efficiently.
Adding JavaScript to JSX
The real power of JSX comes from embedding JavaScript expressions using curly braces {}
:
🚀 Superpower Unlocked!
This is where JSX truly shines! You can mix HTML structure with JavaScript logic seamlessly. It’s like having the best of both worlds in one syntax.
const name = "John";const age = 25;
const element = ( <div> <h1>Hello, {name}!</h1> <p>You are {age} years old.</p> <p>Next year you'll be {age + 1}.</p> </div>);
In above example, we could use JavaScript variables and expressions directly inside the JSX. This allows you to dynamically generate user interfaces based on data.
You can put any valid JavaScript expression inside the curly braces. For example, you can use functions, calculations, or even method calls:
const element = ( <div> <h1>Current Time: {new Date().toLocaleTimeString()}</h1> <p>Random Number: {Math.floor(Math.random() * 100)}</p> <p>2 + 3 = {2 + 3}</p> </div>);
JSX in Attributes
You can use JavaScript expressions in attributes too:
const imageUrl = "https://example.com/image.jpg";const altText = "Beautiful landscape";
const element = <img src={imageUrl} alt={altText} />;
In the above code, we used JavaScript variables imageUrl
and altText
directly in the src
and alt
attributes of the <img>
tag that way
🎯 Pro Tip
Any valid JavaScript expression can go inside {}
- variables, function calls, calculations, or even complex operations!
JSX Attributes vs HTML Attributes
While JSX looks like HTML, some attributes have different names. Here are the key differences and how to know which attributes to use:
Common Attribute Differences:
HTML Attribute | JSX Attribute | Example |
---|---|---|
class | className | <div className=“container”> |
for | htmlFor | <label htmlFor=“email”> |
tabindex | tabIndex | <input tabIndex=“1”> |
readonly | readOnly | <input readOnly> |
maxlength | maxLength | <input maxLength=“10”> |
contenteditable | contentEditable | <div contentEditable> |
Examples:
// HTML form with JSX attributes<form> <label htmlFor="username">Username:</label> <input id="username" type="text" className="form-input" maxLength="20" readOnly={false} tabIndex="1" />
<label htmlFor="message">Message:</label> <textarea id="message" className="form-textarea" rows="4" cols="50" /></form>
Why Are They Different?
JSX attributes follow camelCase naming convention because:
- JSX is JavaScript, and JavaScript uses camelCase,
- Some HTML attributes have the same name as JavaScript reserved words (like
class
) so we cannot use them directly in JSX, - It helps avoid conflicts with JavaScript keywords and makes the code more consistent.
How to Know Which Attribute to Use?
Sometimes it can be tricky to remember which attributes to use in JSX. Here are some tips that we can follow to use proper JSX attributes:
1. React Official Documentation
The best resource is the React DOM Elements documentation. It lists all supported HTML elements and their JSX attributes.
2. General Rule: Use camelCase
Most HTML attributes in JSX follow camelCase:
// HTML: onclick, onchange, onsubmit// JSX: onClick, onChange, onSubmit
<button onClick={handleClick}>Click</button><input onChange={handleChange} /><form onSubmit={handleSubmit}>
3. Your Code Editor
Most modern code editors (like VS Code) will:
- Show autocomplete suggestions for JSX attributes
- Highlight incorrect attribute names
- Provide IntelliSense for available attributes
4. Browser Console
If you use a wrong attribute, React will show a warning in the browser console:
Warning: Invalid DOM property `class`. Did you mean `className`?
Quick Reference Tip
When in doubt about an attribute name, remember: if it’s a single word, it’s usually the same as HTML. If it’s multiple words or conflicts with JavaScript keywords, convert it to camelCase. Your code editor’s autocomplete will also guide you!
Simple Examples
Let’s look at some practical examples:
Example 1: Displaying User Information
const user = { name: "Alice", email: "alice@example.com", age: 28};
const userCard = ( <div className="user-card"> <h2>{user.name}</h2> <p>Email: {user.email}</p> <p>Age: {user.age}</p> </div>);
Example 2: Conditional Display
const isLoggedIn = true;
const message = ( <div> {isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please log in</h1>} </div>);
Common Mistakes to Avoid
🚨 Watch Out!
These are the most common JSX mistakes beginners make. Don’t worry - every React developer has made these mistakes at least once!
1. Forgetting to Close Tags
// ❌ Wrong<input type="text">
// ✅ Correct<input type="text" />
2. Using class Instead of className
// ❌ Wrong<div class="container">
// ✅ Correct<div className="container">
3. Trying to Display Objects Directly
const user = { name: "John", age: 25 };
// ❌ Wrong - This will cause an error<p>{user}</p>
// ✅ Correct - Access specific properties<p>{user.name} is {user.age} years old</p>
Why JSX Makes React Development Easier
- Familiar Syntax: If you know HTML, JSX feels natural
- JavaScript Power: You can use JavaScript expressions anywhere
- Better Readability: Much cleaner than
React.createElement()
calls - IDE Support: Most code editors provide syntax highlighting and autocomplete
Summary
JSX is a syntax that lets you write HTML-like code in JavaScript files. Key points to remember:
- JSX gets converted to
React.createElement()
calls - All tags must be closed
- Use
className
instead ofclass
- Must have one parent element
- Use
{}
to embed JavaScript expressions - JSX makes React code more readable and easier to write
🌱 JSX is confusing?
If JSX feels confusing at first, don’t worry! It’s a powerful tool that becomes easier with practice. The more you use it, the more natural it will feel. Keep experimenting and building small components to get comfortable with JSX syntax.
Next, we will learn about the Virtual DOM and how React uses it to efficiently update the UI. Let’s continue to the Virtual DOM lesson.