What is JSX in React? See Example with Explanation

JSX (JavaScript XML) is a syntax extension in React that allows you to write HTML-like code directly inside JavaScript.
It makes UI creation simple, readable, and intuitive.

Example:

const element = <h1>Hello React!</h1>;

JSX is not required in React, but it is used in 99% of React projects because it improves readability and developer productivity.


Why JSX Is Used

✔ Looks Like HTML, Works Like JavaScript

Easy to understand even for beginners.

✔ Helps Build UI Faster

You can combine logic and UI in one place.

✔ Prevents Errors

JSX compiles to valid JavaScript, catching syntax mistakes early.

✔ Encourages Component-Based Development

Each component simply returns JSX.


How JSX Works Internally

JSX is compiled by Babel into React.createElement() function calls.

Example:

<div className="box">Hello</div>

Turns into:

React.createElement("div", { className: "box" }, "Hello");

This makes JSX both readable and powerful.


Embedding JavaScript in JSX

Use {} to run JavaScript inside JSX.

Example:

const name = "Sagar";
<h2>Hello, {name}</h2>;

You can embed:

  • Variables
  • Functions
  • Expressions
  • Props

JSX Rules You Should Know

  • Use className instead of class
  • Close all tags (even <img />)
  • Wrap multiple elements in one parent
  • Use {} for dynamic values
  • Use fragments (<>...</>) to avoid extra divs

Common Mistakes in JSX

❌ Using class instead of className
❌ Using if directly inside JSX
✔ Use ternary operator instead:

{isLoggedIn ? <Home /> : <Login />}

Conclusion

JSX is one of React’s biggest strengths. It mixes HTML-like syntax with JavaScript, making UI development simple, expressive, and efficient.


Citations

https://savanka.com/category/learn/react/
https://www.w3schools.com/REACT/DEFAULT.ASP

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *