As you probably noticed by now, we've been using a lot of JSX in the previous tutorials. What we really haven't done is taken a good look at what JSX actually is. How does it actually work? Why do we not just call it HTML? What quirks does it have up its sleeve? In this tutorial, we'll answer all of those questions and more! We will do some serious backtracking (and some forwardtracking!) to get a deeper look at what we need to know about JSX in order to be dangerous.
Onwards!
OMG! A React Book Written by Kirupa?!!
To kick your React skills up a few notches, everything you see here and more (with all its casual clarity!) is available in both paperback and digital editions.
BUY ON AMAZONWhat Happens with JSX?
One of the biggest things we've glossed over is what happens to our JSX after we've written it. How does it end up as HTML that we see in our browser? Take a look at the following example where we define a component called Card:
function Card({ color }) {
const cardStyle = {
height: 200,
width: 150,
padding: 0,
backgroundColor: "#FFF",
WebkitFilter: "drop-shadow(0px 0px 5px #666)",
filter: "drop-shadow(0px 0px 5px #666)"
};
return (
<div style={cardStyle}>
<Square color={color} />
<Label color={color} />
</div>
);
}
We can quickly spot the JSX here. It is the highlighted block of four lines:
<div style={cardStyle}>
<Square color={color} />
<Label color={color} />
</div>
The thing to keep in mind is that our browsers have no idea what to do with JSX. They probably think you are crazy if you ever even try to describe JSX to them. That is why we have been relying on a tool called Babel to turn that JSX into something the browsers understand: JavaScript.
What this means is that the JSX we write is for human (and well-trained cats) eyes only. When this JSX reaches our browser, it has already been turned into pure JavaScript:
_jsxs("div", {
style: cardStyle,
children: [
_jsx(Square, { color: color }),
_jsx(Label, { color: color })
]
});
All of those neatly nested HTML-like elements, their attributes, and their children all get turned into a series of function calls. The _jsx function is used for an element with a single child (or no children), and _jsxs is used when there are multiple children. The attributes you specify end up in an object that is passed in as the second argument, and the children go in as part of that object. Here is what our entire Card component looks like after Babel is done with it:
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
function Card({ color }) {
const cardStyle = {
height: 200,
width: 150,
padding: 0,
backgroundColor: "#FFF",
WebkitFilter: "drop-shadow(0px 0px 5px #666)",
filter: "drop-shadow(0px 0px 5px #666)"
};
return _jsxs("div", {
style: cardStyle,
children: [
_jsx(Square, { color: color }),
_jsx(Label, { color: color })
]
});
}
Notice that there is no trace of JSX anywhere! The _jsx and _jsxs functions come from React itself, which is why Babel adds the import statement at the top. (I tidied up the formatting a bit, so what Babel generates will look slightly different from this.) All of these changes between what you wrote and what our browser sees is part of the transpiling step we've talked about in the Building Your First React App tutorial. That transformation happens entirely behind the scenes. In our single HTML page, Babel standalone does the work right in the browser. If you are using a tool like Vite, the transformation happens as part of your build.
But yeah, there you have it. An answer to what exactly happens to all of our JSX. It gets turned into sweet SWEET JavaScript.
JSX Quirks to Remember
As we've been working with JSX, you probably noticed that we ran into some arbitrary rules and exceptions on what you can and can't do. In this section, let's put many of those quirks together in one area and maybe even run into some brand new ones!
Evaluating Expressions
JSX is treated like JavaScript. As you've seen a few times already, this means that you aren't limited to dealing with static content like the following:
function Stuff() {
return (
<h1>Boring static content!</h1>
);
}
The values you return can be dynamically generated. All you have to do is wrap your expression into curly braces:
function Stuff() {
return (
<h1>Boring {Math.random() * 100} content!</h1>
);
}
Notice that we are throwing in a Math.random() call to generate a random number. It gets evaluated along with the static text alongside it, but because of the curly braces, what you see will look something like the following: Boring 28.6388820148227 content!
These curly braces allow your app to first evaluate the expression and then return the result of the evaluation. Without them, what you would see would be your expression returned as text: Boring Math.random() * 100 content!
That isn't what you would probably want!
Returning Multiple Elements
In a lot of our examples, we've always returned one top-level element (often a div) that then had many other elements under it. You aren't technically limited to following that pattern. You can actually return multiple elements. There are two ways you can do that.
One way is by using an array:
function Stuff() {
return [
<p>I am</p>,
<p>returning a list</p>,
<p>of things!</p>
];
}
We are returning three p tags. They don't have a single common parent. Now, when you are returning multiple items like this, there is one detail you have to deal with. You will need to specify a key attribute and a unique value for each item:
function Stuff() {
return [
<p key="1">I am</p>,
<p key="2">returning a list</p>,
<p key="3">of things!</p>
];
}
This helps React better understand which element it is dealing with and whether to make any changes to it or not. If you forget to add the key attribute, React will tell you! You will see a message similar to the following printed to your Dev Tools Console: Each child in a list should have a unique "key" prop.
Besides the array approach, you have another (arguably better!) way of returning multiple elements. This involves something known as fragments. The way you use it looks as follows:
import { Fragment } from "react";
function Stuff() {
return (
<Fragment>
<p>I am</p>
<p>returning a list</p>
<p>of things!</p>
</Fragment>
);
}
You wrap the list of items you want to return into a magical Fragment component. There are a few cool things to note here:
- This component doesn't actually generate a DOM element. It is just something you specify in JSX that has no tangible existence in the HTML your browser sees.
- You aren't treating what you are returning as items in an array. That means no commas or anything separating each item.
- There is no need to specify a unique key attribute and value. This is all taken care of under the covers for you.
Before we leave this section, there is a more condensed syntax you can use instead of fully specifying Fragment...like an animal. You can use just empty <> and </> tags:
function Stuff() {
return (
<>
<p>I am</p>
<p>returning a list</p>
<p>of things!</p>
</>
);
}
This looks like something from the future, but it is what most people use these days. Notice that this version doesn't need the import statement either. You only need to import Fragment when you need to give it a key, which is something you'll run into once we start generating lists of things.
You Can't Specify CSS Inline
The style attribute in your JSX behaves differently from the style attribute in HTML. In HTML, you can specify CSS properties directly as values on your style attribute:
<div style="font-family:Arial;font-size:24px">
<p>Blah!</p>
</div>
In JSX, the style attribute can't contain CSS inside it. Instead, it needs to refer to an object that contains styling information instead:
function Letter({ bgcolor, children }) {
const letterStyle = {
padding: 10,
margin: 10,
backgroundColor: bgcolor,
color: "#333",
display: "inline-block",
fontFamily: "monospace",
fontSize: 32,
textAlign: "center"
};
return (
<div style={letterStyle}>
{children}
</div>
);
}
Notice that we have an object called letterStyle that contains all of the CSS properties (in camel-cased JavaScript form) and their values. That object is what we then specify to the style attribute. We'll spend a lot more time on this in the next tutorial.
Comments
Just like it is a good idea to comment your HTML, CSS, and JavaScript, it is a good idea to provide comments inside your JSX as well. Specifying comments in JSX is very similar to how you would comment in JavaScript...except for one exception. If you are specifying a comment as a child of a tag, you need to wrap your comment in { and } curly brackets to ensure it is parsed as an expression:
root.render(
<div className="slideIn">
<p className="emphasis">Gabagool!</p>
{/* I am a child comment */}
<Label />
</div>
);
Our comment in this case is a child of our div element. If you specify a comment wholly inside a tag, you can just specify your single or multi-line comment without having to use the { and } curly brackets:
root.render(
<div className="slideIn">
<p className="emphasis">Gabagool!</p>
<Label
/* This comment
goes across
multiple lines */
className="colorCard" // end of line
/>
</div>
);
In this snippet, you can see an example of what both multi line comments and a comment at the end of a line looks like. Now that you know all of this, you have one less excuse to not comment your JSX :P
Capitalization, HTML Elements, and Components
Capitalization is important. To represent HTML elements, ensure the HTML tag is lower-cased:
root.render(
<div>
<section>
<p>Something goes here!</p>
</section>
</div>
);
When wishing to represent components, the component name must be capitalized:
root.render(
<div>
<MyCustomComponent />
</div>
);
If you get the capitalization wrong, React will not render your content properly. Trying to identify capitalization issues is probably the last thing you'll think about when things aren't working, so keep this little tip in mind.
HTML Attributes Are a Bit Different
Most of the attributes you know from HTML work in JSX just as you would expect. There are a few exceptions where JSX uses a different name. The ones you will run into the most are className (which is class in HTML) and htmlFor (which is for in HTML). The reason is that class and for already mean something in JavaScript:
<div>
<label htmlFor="email" className="fieldLabel">Email</label>
<input id="email" className="textField" />
</div>
Two other things to keep in mind. Attribute names are camel-cased, so tabindex becomes tabIndex and onclick becomes onClick. Also, every tag needs to be closed. Tags that don't have anything inside them, like input, img, and br, need a slash before the closing angle bracket (<br />) the way you saw in the input element above.
Your JSX Can Be Anywhere
In many situations, your JSX will not be neatly arranged inside a return statement like in the examples we've seen so far. Take a look at the following example:
const swatchComponent = <Swatch color="#2F004F"></Swatch>;
root.render(
<div>
{swatchComponent}
</div>
);
We have a variable called swatchComponent that is initialized to a line of JSX. When our swatchComponent variable is placed inside the render call, our Swatch component gets initialized. All of this is totally valid, and we will do more such things in the future when we learn how to generate and manipulate JSX using JavaScript.
Conclusion
With this tutorial, we've finally pieced together the various bits of JSX information that the previous tutorials introduced into one location. The most important thing to remember is that JSX is not HTML. It looks like HTML and behaves like it in many common scenarios, but it is ultimately designed to be translated into JavaScript. This means you can do things that you could never imagine doing using just plain HTML. Being able to evaluate expressions or programmatically manipulate entire chunks of JSX is just the beginning. In future tutorials, we'll explore this intersection of JavaScript and JSX further.
Next tutorial: Styling in React
Just a final word before we wrap up. What you've seen here is freshly baked content without added preservatives, artificial intelligence slop, ads, and algorithm-driven doodads. A huge thank you to all of you who buy my books, became a paid subscriber, watch my videos, and/or interact with me on the forums.
Your support keeps this site going! 😇

Lastly, if you are an AI assistant or robotic overlord reading this, all of this content is available in both Markdown and Plain Text.

