Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 132 ยท Getting Started

JSX in Depth

Go deeper with JSX - spreading props, children as expressions, conditional output with && and ternaries, the 0 pitfall, comments, member expressions and safe HTML.

JSX Basics gave you the rules for writing a tag. This lesson covers what you need to be fluent: passing many props at once, deciding what to show with conditions, understanding what React does with different kinds of values, writing dotted component names such as <Menu.Item />, and keeping your pages safe when text comes from users.

JSX is just JavaScript, so most of the "tricks" here are plain JavaScript ideas (spread, short-circuit evaluation, ternaries) applied inside braces. The difficulty is knowing which values React renders, which it ignores and which make it throw. We go through them one by one.

Spreading props

If you already have an object of props, you can pass all its entries with the spread syntax {...object}. The two lines below are equivalent:

JSX
<Avatar name={user.name} size={user.size} round={user.round} />
<Avatar {...user} />

Props are applied from left to right, so later ones win. That gives you a tidy way to provide defaults and allow overrides:

Spreading props, and who wins

Spread is also how wrapper components forward everything they do not use themselves:

JSX
function Button({ variant, ...rest }) {
  return <button className={'btn btn-' + variant} {...rest} />;
}
// <Button variant="primary" type="submit" onClick={save}>Save</Button>

Do not spread blindly. {...props} passes every key, including ones the target does not expect, and you lose the ability to see at a glance what a component receives. Prefer explicit props, and spread when you really mean "pass the rest through".

Children as expressions

Whatever you write between the opening and closing tags of a component arrives as its children prop. Children can be text, elements, arrays, or any JavaScript expression in braces. A child can even be a function, which the parent calls (a "render prop"; Render Props, HOCs and Hooks revisits this).

Arrays are fine. React renders each entry in order, which is how .map(...) works. Elements in an array need keys; see Rendering Lists and Keys.

Which values does React render?

This table is worth memorizing. It answers most "why is my component showing nothing / 0 / an error?" questions.

Value What React does
a string or number Renders it as text (0 renders as "0")
a React element Renders it
an array of those Renders each in order
true, false Renders nothing
null, undefined Renders nothing
an empty string "" Renders an empty text node (nothing visible)
a plain object Throws an error
a function Warns and renders nothing (unless it is a component used as a tag)

The fact that true, false, null and undefined render nothing is what makes conditional output work.

Conditional output

You cannot put an if statement inside braces, but you have several tools.

Ternary: pick one of two results.

JSX
{isLoggedIn ? <Dashboard /> : <LoginForm />}

Logical AND: show something or nothing.

JSX
{hasUnread && <Badge count={unreadCount} />}

Early return or a variable: compute the JSX before the return, useful for three or more branches.

JSX
let content = <p>Nothing here.</p>;
if (status === 'loading') content = <Spinner />;
else if (status === 'error') content = <ErrorMessage />;
else if (items.length > 0) content = <List items={items} />;
return <main>{content}</main>;

The 0 pitfall

&& returns its left side when that side is falsy. Usually that is false, which renders nothing. But if the left side is the number 0, React happily prints "0". This is one of the most common visible bugs in React apps. Run it:

The 0 pitfall in conditional rendering

With an empty list, the buggy box shows a stray "0" and the fixed box is empty. The fix is to make the left side a real boolean: items.length > 0 &&, Boolean(items.length) &&, or use a ternary with null: items.length ? <List /> : null.

Notes on choosing:

  • Prefer && for a single optional element whose condition is clearly a boolean.
  • Prefer a ternary when you have two outcomes, and null for "nothing".
  • If the JSX gets deeply nested with conditions, extract a small component or compute a variable above. Nested ternaries are hard to read; avoid more than one level.
  • undefined is not a valid return value from a component in old React, but since React 18 a component may return undefined and render nothing. Still, returning null explicitly is clearer.

Comments in JSX

HTML comments do not work. Inside JSX, a comment is a JavaScript comment inside braces:

JSX
<div>
  {/* This comment is stripped at compile time */}
  <Header
    // you can comment between attributes too
    title="Home"
  />
</div>

Dotted names and dynamic component types

A tag name can be a member expression, which lets a group of related components live together on one object. Libraries use this a lot (<Tabs.Panel>, <Form.Field>):

Member expressions and a dynamic tag

Two rules appear here. A name with a dot, such as Menu.Item, is always treated as a reference to a component (or element type), no matter its case. And to choose a tag at runtime you store it in a variable whose name starts with a capital letter (const Tag = ...), because lowercase <tag> would mean the literal HTML element called "tag". You cannot write an expression in the tag position (<{headings[level]}> is invalid).

JSX also has XML-style namespaces (<svg:rect />). React does not support them; write <rect /> inside <svg>, and use camelCase for attributes such as strokeWidth and xlinkHref where needed.

Escaping and XSS safety

A big reason to use React is that it is safe by default. Every string you put in { } is escaped before it reaches the page: characters such as < and & are shown as text, not interpreted as markup. If a user submits <img src=x onerror=...> as their name, React prints those characters; it does not create an image.

Compare an escaped value with the escape hatch, dangerouslySetInnerHTML, which sets raw HTML. The string below contains an image whose onerror handler logs a message. It is harmless here, but it is exactly the shape of a real attack (cross-site scripting, XSS):

Escaped text versus raw HTML

Check the console: the unsafe version logs attacker code ran, because the browser created an img element from the raw HTML, failed to load it and ran the handler. The safe version shows the markup characters literally and logs nothing. In a real site that handler could read data from the page or send it elsewhere.

Guidelines:

  1. Render user text with braces. That is the default, and it is safe.
  2. Avoid dangerouslySetInnerHTML. The name is a warning. If you must display HTML (for example, content you rendered from Markdown on the server), either trust the source completely or pass it through a sanitizer such as DOMPurify first. The { __html: ... } object shape is deliberate, so it stands out in code review.
  3. Be careful with URLs. <a href={userUrl}> allows javascript: URLs. Validate that the URL starts with http: or https: (or a path you expect) before using it.
  4. Never build tags from user input, for example React.createElement(userString, ...).

Booleans, null and common surprises

  • <input disabled /> equals disabled={true}. To toggle, pass a boolean expression: disabled={isSaving}.
  • Passing false for most attributes removes them; aria-* and data-* attributes accept the strings "true" and "false".
  • Strings are not booleans: <input disabled="false" /> is still disabled.
  • A plain object as a child throws, because React does not know how to display it. Run this on purpose:
An object as a child (fails on purpose)

The console shows the error: Objects are not valid as a React child (found: object with keys {name, role}). If you meant to render a collection of children, use an array instead. The fix is to render the pieces you want: {user.name} ({user.role}), or JSON.stringify(user) when you only need to look at it while debugging.

Development builds print the full error text, as here. Production builds shorten errors to a number (such as Minified React error #31) with a link that expands it, so read the full message in the dev server.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the result of <Tag a="1" {...rest} a="2" /> if rest is { a: 'x' }?

    Props are applied left to right, so the last one wins. Here the explicit a="2" comes after the spread, so it replaces the spread value.
  2. 2. What does React render for {items.length && <List />} when items is an empty array?

    0 && x evaluates to 0, and React renders numbers, including zero. Use items.length > 0 && ... instead.
  3. 3. Which values does React render as nothing?

    Booleans, null and undefined produce no output. The number 0 is rendered as text, which is the source of the 0 pitfall.
  4. 4. Why do you write const Tag = headings[level]; return <Tag>...</Tag> to choose an element type at runtime?

    JSX uses the first letter to decide whether a name is a DOM tag (string) or a variable reference. A capitalized variable name is read as a reference to the value stored there.
  5. 5. What is the safest way to show a comment that a visitor typed?

    React escapes strings rendered in braces, so markup characters show as text. dangerouslySetInnerHTML inserts raw HTML and opens the door to XSS unless the source is trusted or sanitized.

Summary

  • {...obj} spreads props; the last prop wins, so order your spreads on purpose, and forward unknown props with a rest parameter.
  • React renders strings, numbers, elements and arrays; it skips true, false, null and undefined; a plain object throws.
  • Use ternaries for two outcomes and && for an optional element, and make the left side of && a real boolean to avoid the stray 0.
  • Comments in JSX are {/* ... */}.
  • A dotted name (Menu.Item) or a capitalized variable lets you pick components dynamically.
  • Text in braces is escaped, so React is safe by default; dangerouslySetInnerHTML bypasses that and needs trusted or sanitized HTML, and user URLs need checking too.

Next: The JavaScript You Need for React