JSX in React: Write HTML-Like Markup Inside JavaScript
Learn JSX rules step by step: expressions in curly braces, className, style objects, Fragments, self-closing tags, comments, and common JSX errors.
What you will learn
In the first component lesson you wrote markup that looked like HTML inside a JavaScript function. That markup is called JSX. It is the way almost every React component describes its UI, so it is worth learning the rules properly. In this lesson you will learn how JSX works, how to put JavaScript values inside it, which HTML attributes change names, and how to fix the errors beginners meet most often.
You can type the examples into a component file in your own Vite project, such as src/components/ProductHeader.jsx, and render it from App.jsx.
What is JSX?
JSX stands for JavaScript XML. It is a syntax that lets you write HTML-like tags directly inside JavaScript code:
const title = <h1>Hello, JSX!</h1>;
Browsers do not understand JSX. Vite converts it into normal JavaScript before the page runs. Behind the scenes, <h1>Hello, JSX!</h1> becomes a function call that creates a description of an h1 element. You never write those calls yourself. That is the whole point of JSX: it lets you describe the UI in a form that looks like the HTML you already know.
Two helpful facts:
- JSX is not a string and not real HTML. It is JavaScript with a special syntax.
- You do not need
import React from 'react'at the top of every file. The Vite React setup takes care of that.
JSX looks like HTML, but follows stricter rules
JSX is more strict than HTML. Browsers forgive many HTML mistakes, but JSX stops with an error. Here are the rules, one by one.
Rule 1: Return one top-level element
A component can return only one root element. This fails:
function Welcome() {
return <h2>Hello</h2><p>World</p>;
}
Wrap the elements in a <div>, or use a Fragment (<>...</>) when you do not want an extra element in the page:
function Welcome() {
return (
<>
<h2>Hello</h2>
<p>World</p>
</>
);
}
When your JSX spans several lines, put it in parentheses after return. If you write return and then start the JSX on the next line without parentheses, JavaScript ends the statement right after return and the function returns nothing.
Rule 2: Close every tag
In HTML you can write <br> or <img src="a.png">. In JSX, every tag must be closed. Elements with no content are self-closing:
<br />
<img src="/logo.png" alt="Logo" />
<input type="text" />
<ProfileCard />
Rule 3: Use camelCase attribute names
Most attributes keep their HTML names (id, href, src, alt, type). A few are different, because JSX attributes become JavaScript property names:
| HTML | JSX | Why |
|---|---|---|
class |
className |
class is a reserved word in JavaScript |
for (on a label) |
htmlFor |
for is a reserved word too |
tabindex |
tabIndex |
multi-word names use camelCase |
onclick |
onClick |
event names use camelCase |
maxlength |
maxLength |
camelCase |
style="color: red" |
style={{ color: "red" }} |
style takes an object (see below) |
data-* and aria-* attributes keep their hyphens: data-id="5" and aria-label="Close" are written exactly as in HTML.
Put JavaScript inside JSX with curly braces
The most useful part of JSX is the ability to mix JavaScript values into the markup. Wrap the value in curly braces { }. Whatever is inside the braces is JavaScript:
function ProductHeader() {
const name = "Wireless Mouse";
const price = 24.5;
const quantity = 2;
return (
<header className="product-header">
<h2>{name}</h2>
<p>Price: ${price}</p>
<p>Total for {quantity}: ${(price * quantity).toFixed(2)}</p>
</header>
);
}
export default ProductHeader;
Line by line:
- The variables
name,priceandquantityare normal JavaScript, written above thereturn. {name}puts the value ofnameinside the heading.- In
Price: ${price}, the$is just a dollar sign in the text, and{price}is the JavaScript value. Together they show$24.5. {(price * quantity).toFixed(2)}runs a calculation and a method call, then shows the result.
Render <ProductHeader /> in App.jsx. The browser shows:
Wireless Mouse
Price: $24.5
Total for 2: $49.00
What can go inside the braces?
Anything that is a JavaScript expression, meaning anything that produces a value:
<div>
<p>{user.name}</p>
<p>{2 + 3}</p>
<p>{name.toUpperCase()}</p>
<p>{isMember ? "Member" : "Guest"}</p>
<p>{formatPrice(price)}</p>
</div>
In order, these show a property of an object, the result of a calculation, the result of a method call, the result of a ternary, and the result of a function call.
You cannot put statements such as if, for or let inside braces. Do those before the return, or use an expression such as a ternary. You will learn the usual patterns in the conditional rendering and lists lessons.
What React does with different values
Value inside { } |
What appears on the page |
|---|---|
| A string or a number | The text |
true, false, null, undefined |
Nothing |
| An array of strings, numbers or JSX | Every item, one after another |
A plain object like { name: "Aisha" } |
An error (objects cannot be displayed directly) |
That “nothing” rule for true, false and null is what makes conditional rendering possible later.
Dynamic attributes
Use braces for attribute values that come from JavaScript. Use quotes for fixed text:
const productUrl = "https://example.com/mouse";
// Dynamic value: use braces
<a href={productUrl}>View product</a>
// Fixed text: use quotes
<a href="https://example.com">Home</a>
Never put braces inside quotes. href="{productUrl}" sets the link to the literal text {productUrl}.
You can also pass booleans and numbers:
<input type="number" min="1" disabled={false} />
// These two buttons are identical
<button disabled={true}>Save</button>
<button disabled>Save</button>
The style attribute takes an object
In HTML, style is a string. In JSX, style takes a JavaScript object, and its property names are written in camelCase:
<p style={{ color: "green", fontWeight: "bold" }}>In stock</p>
The double braces are not special syntax. The outer { } means “JavaScript goes here”, and the inner { } is the object { color: "green", fontWeight: "bold" }. Compare it with CSS: font-weight becomes fontWeight, and background-color becomes backgroundColor.
For most styling, a CSS class is better than inline styles. The styling lesson explains when to use which.
Comments in JSX
An HTML comment (<!-- -->) does not work in JSX. Inside the markup, write a JavaScript comment in braces:
<header>
{/* This is a JSX comment */}
<h2>{name}</h2>
</header>
Above the return, normal // comments work as usual.
JSX is safe by default
React escapes every value you put in braces before showing it. If a variable contains HTML-like text, React shows it as plain text and does not run it:
const comment = "<b>Hello</b>";
<p>{comment}</p>
The page shows the characters <b>Hello</b> as text, not bold text. This protects your page from a type of attack called cross-site scripting (XSS), where someone types malicious HTML into a form. You will not need anything unsafe in normal React code.
JSX versus HTML: quick comparison
| HTML | JSX | |
|---|---|---|
| Root elements | Many allowed | One (or a Fragment) |
| Void tags | <br>, <img> |
<br />, <img /> |
| CSS class | class |
className |
| Label target | for |
htmlFor |
| Events | onclick="..." (string) |
onClick={function} |
| Inline style | style="color: red" |
style={{ color: "red" }} |
| Dynamic values | Not possible | {expression} |
| Comments | <!-- ... --> |
{/* ... */} |
A complete example
Put everything together in one component:
function ProductHeader() {
const name = "Wireless Mouse";
const price = 24.5;
const quantity = 2;
const productUrl = "https://example.com/mouse";
return (
<header className="product-header">
{/* This is a JSX comment */}
<h2>{name}</h2>
<p>Price: ${price}</p>
<p>Total for {quantity}: ${(price * quantity).toFixed(2)}</p>
<p style={{ color: "green", fontWeight: "bold" }}>In stock</p>
<a href={productUrl}>View product</a>
<label htmlFor="qty">Quantity</label>
<input id="qty" type="number" min="1" placeholder="1" />
<br />
</header>
);
}
export default ProductHeader;
Expected result in the browser: a heading Wireless Mouse, the lines Price: $24.5 and Total for 2: $49.00, the word In stock in bold green, a link, and a labelled number box. Clicking the label Quantity puts the cursor in the input, because htmlFor="qty" matches the input’s id.
Common mistakes
1. Using class instead of className. React shows a console warning like Invalid DOM property class. Did you mean className? Use className.
2. Forgetting to close a tag. <img src="a.png"> or <input> without / makes the build fail. Write <img src="a.png" alt="" />.
3. Putting an object between braces.
const user = { name: "Aisha" };
<p>{user}</p>
React throws: Objects are not valid as a React child (found: object with keys {name}). Show a property instead: {user.name}.
4. Writing style as a string.
<p style="color: red">Hi</p>
This throws: The `style` prop expects a mapping from style properties to values, not a string. Use style={{ color: "red" }}.
5. Putting braces inside quotes. <a href="{url}"> is the literal text {url}. Remove the quotes: <a href={url}>.
6. Using if or for inside braces. Statements are not allowed there. Use a ternary, or compute the value above the return.
7. Two root elements. Vite reports Adjacent JSX elements must be wrapped in an enclosing tag. Add a Fragment or a wrapper element.
8. Starting JSX on a new line after return. Use return ( and put the JSX inside the parentheses, or the function returns undefined and nothing appears.
Practice
-
Create a
BookInfocomponent with variables for a title, an author and a price. Show them in anh2and twopelements using curly braces, and render it inApp.jsx. -
Predict, then check: What does
<p>{3 * 4}</p>show? What does<p>{"3 * 4"}</p>show? What does<p>{true}</p>show? -
In
BookInfo, show the price with a$sign and two decimal places, usingtoFixed(2). -
Add a
styleto the title so it is dark blue and 28 pixels high. Which property names do you need in camelCase? -
Debug: This code gives an error. Name three things that are wrong.
function Greeting() { return ( <div class="greeting"> <img src="/hello.png"> <p style="color: red">Hello</p> </div> ); } -
Debug: Your page crashes with
Objects are not valid as a React child. You wrote<p>{person}</p>wherepersonis{ name: "Ravi", age: 20 }. Fix it in two different ways. -
Create a form snippet with a
labeland aninputthat are properly connected usinghtmlForandid. Click the label in the browser to check that the input gets focus. -
Store the text
<em>Welcome</em>in a variable and show it with{ }. What do you see, and why is that useful for safety?
Recap
- JSX is HTML-like syntax inside JavaScript. Vite turns it into plain JavaScript for the browser.
- A component returns one root element. Use a Fragment (
<>...</>) to avoid an extra wrapper. - Close every tag, and use self-closing tags such as
<br />and<input />. - Use camelCase attributes:
className,htmlFor,tabIndex,onClick.data-*andaria-*keep their hyphens. - Use
{ }to put any JavaScript expression in the markup, for text and for attribute values. styletakes an object:style={{ fontWeight: "bold" }}.- Comments are written as
{/* ... */}inside JSX. - React escapes values, so JSX is safe against injected HTML by default.
- Next you will make components flexible by passing data into them with props.
Frequently asked questions
Is JSX required to use React?
No. React can be used without JSX by calling its functions directly, but that is hard to read. Almost every React project uses JSX, and all the examples in this course use it.
Is JSX the same as HTML?
No. It looks like HTML, but it is JavaScript syntax with stricter rules and a few different attribute names. It also lets you insert JavaScript values with { }, which HTML cannot do.
Why does React use className instead of class?
JSX attributes become JavaScript object properties, and class is a reserved word in JavaScript (used for classes). So React uses className. The same reason applies to htmlFor instead of for.
Why are there two curly braces in style={{ color: "red" }}?
The outer braces tell JSX that JavaScript follows. The inner braces are the JavaScript object that holds the style properties. It is one pair of braces inside another, not a special double-brace syntax.
Why does {true} or {null} show nothing?
React deliberately skips true, false, null and undefined when rendering. This lets you write conditions in JSX, such as showing an element only when a value is true. You will use this in the conditional rendering lesson.
Can I write JSX in a .js file?
With the default Vite React setup, put JSX in files that end in .jsx. A .js file that contains JSX causes an error such as Unexpected JSX expression.
See also: Your First React Component, HTML Attributes in Depth, JavaScript Operators, JavaScript Objects