VITSOLS
2025-10-03
In this article, you’ll learn:
- What JSX is
- Why React uses JSX
- How JSX differs from HTML
- Real-world examples
- Common mistakes developers face
🚀 What is JSX in React?
JSX (JavaScript XML) is a syntax extension for JavaScript used in React. It allows you to write HTML-like code inside JavaScript, making your UI components more readable and intuitive.
jsx
const element = <h1> Welcome to React </h1>;
This looks like HTML—but it’s actually JSX, which React converts into JavaScript behind the scenes.
💡 Why Use JSX?
| Benefit | Description |
|---|---|
| Readable UI Code | JSX looks like HTML, making component structure easy to understand. |
| Faster Development | Write UI directly inside JavaScript without separate templates. |
| Use JavaScript Logic | Embed variables and functions using curly braces {}. |
| Component-Based | Perfect for building reusable and modular UI components. |
🔍 JSX vs HTML – What’s the Difference?
| HTML | JSX |
|---|---|
Uses class attribute |
Uses className instead of class |
| Static content | Dynamic with JavaScript expressions |
| No embedding JS | Supports JS with {} syntax |
| Less component-friendly | Built for reusable components |
Example: HTML vs JSX
❌ HTML (Not Valid in JSX)
html
<h1 class:'title'> Hello </h1>;
✅ JSX
jsx
<h1 className:'title'> Hello </h1>;
🧪 Embedding JavaScript in JSX
You can include JavaScript expressions inside JSX using curly braces {}.
jsx
const name = 'VITSOLS';
const greeting = <h2> Welcome, {name}! </h2>;
🧱 JSX in a Functional Component
jsx
function Welcome() {
const user = "John";
return <h1>Hello, {user}! This is JSX in action.</h1>;
}
export default Welcome;
🔁 JSX Must Have One Parent Element
jsx
return (
<>
<h1>Title</h1>;
<h1>Description goes here.</h1>;
</>
);
⚠️ Common JSX Errors & Fixes
| Mistake | Reason / Fix |
|---|---|
Using class instead of className |
class is a JavaScript keyword, use className. |
| Missing closing tags | All tags like <img/> must be self-closed. |
| Multiple root elements | Wrap elements inside one parent <div> or <></>. |
| Improper JavaScript expressions | Enclose JS code in {} brackets only. |
🌍 Real-Time Use Cases of JSX
| Use Case | How JSX Helps |
|---|---|
| Dynamic Dashboards | Easy to render real-time data using JavaScript expressions. |
| Conditional Rendering | Show/hide UI elements with JS logic. |
| Component Libraries | Build reusable cards, buttons, forms using JSX. |
| Interactive UI | Combine events and UI directly in code. |