Sub topic 4
Writing markup with JSX
This chapter assumes you know JavaScript functions, objects, arrays and ES modules, and basic HTML. It covers JSX: what it is, the rules it enforces, and the errors you will meet first.
What JSX is
JSX is a syntax extension for JavaScript that lets you write markup inside a component. A build tool turns each JSX element into a plain JavaScript function call before the browser sees it. The browser never runs JSX directly, which is one reason React projects need a build tool.
function Greeting() {
return <h1 className="title">Hello</h1>
}After the build step, this becomes a call that creates an object describing an h1 element with a title class. React uses these objects to decide what to put on the page.
Embedding JavaScript with curly braces
Curly braces switch from markup back to JavaScript. Any expression can go inside them: a variable, a function call, a ternary, or a template string. Statements such as if and for cannot.
function Profile() {
const user = { name: 'Ada', online: true }
const tags = ['math', 'code']
return (
<section>
<h2>{user.name.toUpperCase()}</h2>
<p>{user.online ? 'Online' : 'Offline'}</p>
<ul>
{tags.map((tag) => (
<li key={tag}>{tag}</li>
))}
</ul>
</section>
)
}
export default ProfileThe key prop on each list item lets React track items between renders. Use a stable value such as an id, not the array index when the list can be reordered.
How JSX differs from HTML
JSX looks like HTML but follows JavaScript rules.
| HTML | JSX | Reason |
|---|---|---|
| `class="box"` | `className="box"` | `class` is a reserved word in JavaScript |
| `for="email"` | `htmlFor="email"` | `for` is a reserved word |
| `onclick="run()"` | `onClick={run}` | Handlers are camelCase and receive a function |
| `style="color: red"` | `style={{ color: 'red' }}` | `style` takes an object |
| `<br>` | `<br />` | Every tag must be closed |
The double braces in style={{ color: 'red' }} are not special syntax. The outer pair enters JavaScript and the inner pair is an object literal.
One root element
A component returns a single root element. To return siblings without adding an extra div, wrap them in a fragment, written <> and </>.
function Header() {
return (
<>
<h1>Title</h1>
<p>Subtitle</p>
</>
)
}Components versus elements
Names that start with a lowercase letter, like <div>, are built-in HTML elements. Names that start with an uppercase letter, like <Header />, refer to components. If you write <header /> when you meant your component, React renders the plain HTML tag instead.
Common errors
- Writing
classinstead ofclassNameproduces a console warning and the class may not apply. - Using
onClick={run()}callsrunduring rendering. Pass the function itself:onClick={run}, oronClick={() => run(id)}when you need arguments. - Putting an object directly in braces, such as
{user}, throws "Objects are not valid as a React child". Render one of its fields instead. - Saving JSX in a file ending in
.jscan fail in Vite. Use the.jsxextension.
Exercise
This component has three JSX mistakes. Name them and give the corrected code. function Card() { return ( <div class="card" onClick={alert('hi')}> <img src="a.png"> </div> ) }
Show answer
First, class must be className. Second, onClick={alert('hi')} runs the alert during rendering, so pass a function: onClick={() => alert('hi')}. Third, <img> must be self-closed. Corrected:
function Card() {
return (
<div className="card" onClick={() => alert('hi')}>
<img src="a.png" />
</div>
)
}