Sub topic 4
Writing markup with JSX
This chapter assumes you know HTML and CSS, JavaScript functions, objects, arrays and ES modules, and that you have read the earlier chapters on components. JSX is the syntax you use inside components to describe what they render.
What JSX is
JSX is a syntax extension for JavaScript that lets you write markup inside a .jsx file. It looks like HTML, but it is not HTML and browsers cannot run it. A build tool such as Vite, through its React plugin, compiles each JSX element into a plain JavaScript function call before the code reaches the browser.
const heading = <h1 className="title">Hello</h1>After compilation, that line becomes a call to a function from React's JSX runtime. The result is a plain JavaScript object that describes an h1 element with a className of "title" and the text Hello. React reads these objects to decide what to put on the screen.
This is why a JSX element is a value. You can store it in a variable, pass it to a function, return it from a function, or put it in an array.
Embedding JavaScript with curly braces
Curly braces switch from markup back to JavaScript. Inside them you can put any JavaScript expression, meaning anything that produces a value.
function Greeting({ name, unread }) {
const year = new Date().getFullYear()
return (
<section>
<h2>Hello, {name.toUpperCase()}</h2>
<p>You have {unread} unread {unread === 1 ? 'message' : 'messages'}.</p>
<p>Copyright {year}</p>
</section>
)
}
export default GreetingYou can use braces in two places:
- As the content of an element, as in
<h2>Hello, {name}</h2>. - As the value of an attribute, as in
<img src={photoUrl} />.
Statements such as if, for and const are not expressions, so they cannot go inside braces. Put them above the return, as year is in the example.
If you write quotes around an attribute value, as in src="photoUrl", React treats it as the literal string photoUrl. Write src={photoUrl} to use the variable.
Rules that differ from HTML
JSX follows stricter rules than HTML. Most early errors come from the following.
- Return one root element. A component can return only one top-level element. Wrap siblings in a parent element, or in a fragment, written
<>...</>, which adds nothing to the page. - Close every tag. HTML allows
<br>and<img>. JSX requires<br />and<img />. - Use camelCase attribute names.
classbecomesclassName,forbecomeshtmlFor, andtabindexbecomestabIndex. Bothclassandforare reserved words in JavaScript. - Pass
styleas an object. The double braces instyle={{ color: 'red' }}are one pair for the JavaScript expression and one pair for the object literal. CSS property names are camelCase, as inbackgroundColor. - Capitalize component names.
<Counter />refers to a component.<counter />is treated as an HTML tag namedcounter.
function Profile({ photoUrl }) {
return (
<>
<img src={photoUrl} alt="Profile" className="avatar" />
<label htmlFor="bio">Bio</label>
<textarea id="bio" style={{ backgroundColor: '#f4f4f4' }} />
</>
)
}
export default ProfileHow JSX becomes JavaScript
The compiler rewrites each element into a call to jsx(), imported automatically from react/jsx-runtime. The output below is roughly what your code turns into.
import { jsx as _jsx } from 'react/jsx-runtime'
const heading = _jsx('h1', { className: 'title', children: 'Hello' })Two details follow from this.
- Lowercase tag names become strings (
'h1'). Capitalized names become references to the function or variable with that name (Counter). - Everything between the opening and closing tags becomes the
childrenprop. This is how a component receives nested content.
You no longer need import React from 'react' at the top of each file. The modern JSX transform imports the runtime for you.
function Card({ title, children }) {
return (
<div className="card">
<h3>{title}</h3>
{children}
</div>
)
}
export default CardUsing it as <Card title="Tips"><p>Drink water.</p></Card> puts the <p> element in children.
Rendering conditions
Because if is a statement, you choose what to show with expressions. Three patterns cover most cases.
function Status({ isLoggedIn, errorCount }) {
if (!isLoggedIn) {
return <p>Please sign in.</p>
}
return (
<div>
<p>{isLoggedIn ? 'Welcome back' : 'Welcome'}</p>
{errorCount > 0 && <p>{errorCount} errors found.</p>}
</div>
)
}
export default Status- Early return with a normal
ifhandles whole-component cases. - The ternary operator (
condition ? a : b) chooses between two pieces of markup. - The
&&operator shows something or nothing.
Rendering rules for values matter here. null, undefined, true and false render nothing. The number 0 does render, as the text 0. If you write {count && <List />} and count is 0, the page shows a stray 0. Write {count > 0 && <List />} instead.
Rendering lists
To render an array, use map to turn each item into an element.
const tasks = [
{ id: 1, text: 'Install Node.js' },
{ id: 2, text: 'Create the app' },
{ id: 3, text: 'Edit App.jsx' },
]
function TaskList() {
return (
<ul>
{tasks.map((task) => (
<li key={task.id}>{task.text}</li>
))}
</ul>
)
}
export default TaskListEach element in a list needs a key prop that is unique among its siblings. React uses keys to match items between renders, so it can tell which one was added, removed or moved.
- Use a stable identifier from your data, such as a database ID.
- Avoid the array index as a key when the list can be reordered, filtered or have items inserted. Component state can then attach to the wrong item.
- Do not generate keys with
Math.random(). A new key on every render makes React discard and rebuild each item.
A missing key produces a warning in the browser console during development.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| "Adjacent JSX elements must be wrapped in an enclosing tag" | Component returns two root elements | Wrap them in `<>...</>` |
| Console warning about `class` | HTML attribute name used | Use `className` |
| "Objects are not valid as a React child" | An object such as `{user}` was placed in braces | Render a field, such as `{user.name}` |
| Stray `0` on the page | `count && <X />` with `count` equal to `0` | Compare explicitly: `count > 0 && <X />` |
| Component renders as an unknown lowercase tag | Component name starts with a lowercase letter | Rename it, for example `Counter` |
| "Each child in a list should have a unique key" | `map` output without `key` | Add `key={item.id}` |
Exercise
A component receives items, an array of { id, name } objects, and showCount, a number. It should render a <ul> of names and, only when showCount is greater than zero, a paragraph reading "Showing N items". Write the component. Explain what happens if you write {showCount && <p>...</p>} and showCount is 0.
Show answer
function ItemList({ items, showCount }) { return (<div><ul>{items.map((item) => (<li key={item.id}>{item.name}</li>))}</ul>{showCount > 0 && <p>Showing {showCount} items</p>}</div>) } With {showCount && <p>...</p>} and a value of 0, the expression evaluates to the number 0. React renders numbers, so the page shows a stray "0". The explicit comparison showCount > 0 produces false, which renders nothing.
Exercise
Fix this JSX so it compiles and behaves correctly: return (<label for="name">Name</label><input class="field" style="color: red">)
Show answer
Wrap the siblings in a fragment, rename the attributes, make the style an object, and close the input tag: return (<><label htmlFor="name">Name</label><input className="field" style={{ color: 'red' }} /></>)