Sub topic 2
Writing markup with JSX
This chapter covers the syntax rules of JSX. It assumes you can write function components (the previous chapter), and that you know modern JavaScript (arrow functions, destructuring, ES modules) and basic HTML elements. Later chapters cover embedding expressions, attributes, fragments, and the compiled output in detail. Here the focus is on what makes a piece of JSX valid.
What JSX is
JSX is a syntax extension for JavaScript that lets you write element descriptions that look like HTML. Browsers cannot run it. A build tool such as Babel, SWC, esbuild, or TypeScript compiles each JSX element into a plain JavaScript function call before the code reaches the browser.
Each JSX element is an expression. It produces a value (a React element, which is a plain object describing what to render). You can store it in a variable, return it from a function, or pass it as an argument, like any other value.
const heading = <h1>Hello</h1>;
function Page() {
return heading;
}JSX is not HTML. It follows HTML's look, but the rules come from JavaScript and XML. Most JSX errors come from carrying HTML habits over to it.
Rule 1: return a single root element
A component returns one value, and one JSX expression produces one element. Two sibling elements side by side are therefore an error.
// Syntax error: adjacent JSX elements must be wrapped in an enclosing tag
function Broken() {
return (
<h1>Title</h1>
<p>Body</p>
);
}The simplest fix is to wrap the siblings in a parent element.
function Article() {
return (
<article>
<h1>Title</h1>
<p>Body</p>
</article>
);
}A wrapper div is not always what you want, because it adds an extra node to the DOM and can break CSS layouts such as grids and tables. The fragments chapter shows how to group elements without a wrapper.
Rule 2: close every tag
HTML lets you leave some tags open, such as <li> or <p>, and the browser guesses where they end. JSX does not guess. Every element must be closed, either with a closing tag or by self-closing.
function Form() {
return (
<form>
<label>
Name
<input type="text" />
</label>
<br />
<button type="submit">Send</button>
</form>
);
}Elements that have no content in HTML, such as <img>, <br>, <hr>, and <input>, must be written with a trailing slash: <img />. You can also self-close your own components when they have no children: <Avatar />.
Rule 3: parentheses after return
JavaScript inserts a semicolon automatically after a bare return that is followed by a line break. If your JSX starts on the next line without parentheses, the function returns undefined.
function Wrong() {
return
<h1>Never rendered</h1>;
}
function Right() {
return (
<h1>Rendered</h1>
);
}Wrong runs, and React then receives undefined. Wrapping multi-line JSX in parentheses puts the opening of the expression on the same line as return, so no semicolon is inserted. A formatter such as Prettier adds these parentheses for you.
Rule 4: capitalization decides what a tag means
The first letter of a tag name tells the compiler how to treat it.
| Tag | Meaning | Compiled argument |
|---|---|---|
| `<div>` | Built-in DOM element | The string `'div'` |
| `<Greeting>` | Component | The variable `Greeting` |
| `<Menu.Item>` | Component stored on an object | The expression `Menu.Item` |
A lowercase tag is always a string naming a DOM element. An uppercase tag is looked up as a JavaScript variable, so the component must be in scope, either defined in the file or imported.
import Greeting from './Greeting.jsx';
function App() {
return (
<main>
<Greeting />
</main>
);
}
export default App;Two failures are common here:
- Naming a component in lowercase, such as
function greeting(), then writing<greeting />. React treats it as an unknown DOM element and renders an empty<greeting>tag in the page. It does not call your function. - Forgetting to import an uppercase component. This raises a
ReferenceErrorsuch asGreeting is not defined.
The diagram shows how the compiler decides.
Rule 5: text, whitespace, and special characters
JSX handles whitespace differently from both HTML and plain strings. The rules are:
- Whitespace at the start and end of a line inside an element is removed.
- Blank lines are removed.
- Line breaks between text pieces become a single space.
- Spaces between words on the same line are kept.
function Whitespace() {
return (
<p>
Hello,
world
</p>
);
}This renders Hello, world as one line of text, with a single space where the line break was. A line break between two elements, however, produces no space at all. The next component shows the effect.
function Names() {
return (
<p>
<b>Ada</b>
<i>Lovelace</i>
</p>
);
}The output reads AdaLovelace. To keep a space, put an explicit one in a JavaScript string expression, or place the elements on the same line.
function NamesSpaced() {
return (
<p>
<b>Ada</b>{' '}
<i>Lovelace</i>
</p>
);
}Some characters have a special meaning in JSX text. The less-than sign < starts a tag, and curly braces { and } start an expression, so you cannot type them as literal text. Use an HTML entity, or put the character in a string expression.
function Escapes() {
return (
<p>
1 < 2 and a brace: {'{'} and a space: done
</p>
);
}HTML entities such as <, &, and work in JSX text. They do not work inside a JavaScript string: {'<'} prints the six characters <.
Rule 6: comments need braces
An HTML comment <!-- --> is a syntax error in JSX. A JavaScript comment written directly among child elements would be rendered as text. To comment inside JSX markup, wrap a block comment in curly braces.
function Commented() {
return (
<div>
{/* This comment is not rendered */}
<p>Visible</p>
</div>
);
}Inside a tag's own attribute list, you can use ordinary /* */ or // comments, because that area is JavaScript-like syntax rather than child content.
function Input() {
return (
<input
type="text"
// a line comment between attributes
placeholder="Name"
/>
);
}Rule 7: some names differ from HTML
Because JSX attributes become JavaScript object keys, attribute names follow JavaScript naming. class is a reserved word in JavaScript, so you write className. The HTML attribute for becomes htmlFor. Multi-word attributes use camelCase, such as tabIndex and onClick. A later chapter covers attributes in full. For now, remember that copying HTML into JSX needs this renaming pass.
function Field() {
return (
<div className="field">
<label htmlFor="email">Email</label>
<input id="email" type="email" tabIndex={1} />
</div>
);
}React warns in the browser console when you use class instead of className. The page may still look right, but treat the warning as a bug.
Common error messages
| Message | Likely cause | Fix |
|---|---|---|
| Adjacent JSX elements must be wrapped in an enclosing tag | Two sibling roots in a `return` | Wrap them in one parent |
| Unterminated JSX contents | A tag was never closed, or `</` does not match | Close each tag, and check the nesting |
| `X is not defined` | Uppercase tag with no import or definition | Import or define the component |
| Nothing renders, no error | `return` followed by a line break | Add parentheses after `return` |
| Unexpected token `<` in a `.js` file | The build tool does not process JSX in that file | Rename to `.jsx` or configure the tool |
Putting the rules together
The component below follows every rule in this chapter.
import { useState } from 'react';
function Newsletter() {
const [subscribed, setSubscribed] = useState(false);
return (
<section className="newsletter">
{/* The label is tied to the input by id */}
<label htmlFor="email">Email</label>
<input id="email" type="email" />
<br />
<button type="button" onClick={() => setSubscribed(true)}>
Subscribe
</button>
<p>{subscribed ? 'Thanks!' : 'Not subscribed yet.'}</p>
</section>
);
}
export default Newsletter;It has one root, section. The input and br are self-closed. The return is wrapped in parentheses. The comment sits inside braces. It uses className and htmlFor. The curly braces around the ternary and onClick are the topic of the next chapter.
Exercise
The component below renders nothing and the console shows no JSX syntax error. Name two separate problems that would stop it from working as intended, and fix them. function badge() { return <span class="badge">New</span> } export default function App() { return <badge />; }
Show answer
First, the return is followed by a line break, so JavaScript inserts a semicolon and the function returns undefined. Wrap the JSX in parentheses that start on the return line. Second, badge starts with a lowercase letter, so <badge /> is treated as a DOM element named "badge" and the function is never called. Rename it to Badge and use <Badge />. Also change class to className. The fixed code is:
function Badge() {
return (
<span className="badge">New</span>
);
}
export default function App() {
return <Badge />;
}
Exercise
You write <p><b>Ada</b> on one line, then <i>Lovelace</i></p> on the next line, and the page shows "AdaLovelace" with no space. Why, and how do you fix it?
Show answer
JSX removes a line break between two elements and does not turn it into a space. Add an explicit space, for example {' '} after the closing </b>, or put both elements on the same line separated by a normal space.