JSX is one of the most important concepts in React and often the most confusing for beginners.
In this lesson, you will learn what JSX is, why it exists, and how to use it correctly to build dynamic user interfaces.
What Is JSX?
JSX stands for JavaScript XML.
It is a syntax extension that allows you to write HTML-like code inside JavaScript files.
Although JSX looks like HTML, it is not HTML.
JSX is transformed into regular JavaScript function calls before running in the browser.
Why React Uses JSX
JSX makes UI code easier to read and maintain by keeping structure and logic together.
Without JSX, UI code becomes verbose and harder to understand.
With JSX, React components remain clear and expressive.
JSX allows you to:
- Combine logic and markup
- Embed JavaScript expressions in UI
- Create readable component structures
JSX Behind the Scenes
JSX is converted into JavaScript using a build tool such as Babel.
This JSX code:
const element = <h1>Hello React</h1>;Is transformed into:
const element = React.createElement("h1", null, "Hello React");This is why JSX must be valid JavaScript.
JSX Syntax Rules
JSX follows specific rules:
- JSX must return one parent element
- All tags must be properly closed
- Use camelCase for attributes
- Use className instead of class
Example:
function App() {
return (
<div className="container">
<h1>Welcome</h1>
<p>React JSX example</p>
</div>
);
}Embedding JavaScript in JSX
You can embed JavaScript expressions using curly braces .
const name = "Emre";
function Greeting() {
return <h2>Hello, {name}</h2>;
}Valid expressions include:
- Variables
- Function calls
- Mathematical operations
- Ternary expressions
Statements like if or for are not allowed directly inside JSX.
Conditional Rendering in JSX
Use ternary operators for conditions.
function Status() {
const isLoggedIn = true;
return (
<p>{isLoggedIn ? "Welcome back" : "Please log in"}</p>
);
}JSX and Styling
Inline styles are written as JavaScript objects.
const style = {
color: "blue",
fontSize: "18px"
};
function Title() {
return <h1 style={style}>Styled Title</h1>;
}JSX Comments
Use JavaScript comments inside curly braces.
function App() {
return (
<div>
{/* This is a JSX comment */}
<h1>Hello JSX</h1>
</div>
);
}Common JSX Mistakes
- Forgetting to close tags
- Using class instead of className
- Returning multiple elements without a wrapper
- Writing statements inside JSX
Understanding these rules prevents many beginner errors.
Summary
In this lesson, you learned:
- What JSX is and why it exists
- How JSX is transformed into JavaScript
- Core JSX syntax rules
- How to embed JavaScript expressions
- Conditional rendering basics
- Styling and comments in JSX
In the next lesson, we will explore React Components and learn how to structure applications using reusable building blocks.