Sub topic 1
Elements, Components, and JSX: What a Component Returns
Every re-render starts with a component function that returns something. To follow how React decides what to change, you first need to know what that something is. It is not DOM nodes and not HTML. This chapter covers what JSX turns into, what a React element is, and how elements differ from components. It also covers the values a component is allowed to return.
Prerequisites
This chapter assumes you have:
- Working knowledge of JavaScript functions, objects, and arrays.
- Written basic React components that take props and return JSX.
- Used the
useStatehook. - A basic idea of what the browser DOM is.
You do not need to know anything about reconciliation or the commit phase yet. Later chapters cover them.
JSX is syntax for function calls
Browsers do not understand JSX. A build tool such as Babel, SWC, or esbuild rewrites each JSX tag into a function call before the code runs. The classic form of that call is React.createElement. Modern toolchains emit a call to jsx from react/jsx-runtime instead. The result is the same kind of object.
This example is written with createElement so it runs in Node.js as an ES module without a build step:
import { createElement } from 'react';
function Greeting({ name }) {
return createElement('h1', { className: 'title' }, 'Hello, ', name);
}
// Equivalent to: <Greeting name="Ada" />
const element = createElement(Greeting, { name: 'Ada' });
console.log(element.type === Greeting); // true
console.log(element.props); // { name: 'Ada' }In JSX, <Greeting name="Ada" /> compiles to the same call as the last createElement line. The first argument is the element's type. The second is the props object. Any further arguments become the children prop.
Curly braces in JSX hold any JavaScript expression. They are not a template language. {items.map(...)} is ordinary JavaScript that produces an array, and JSX places that array in the children.
An element is a plain object
createElement returns a small, plain JavaScript object called a React element. Here is a simplified view of what <button className="primary">Save</button> produces. Real elements carry a few extra internal fields that vary between React versions.
const element = {
$$typeof: Symbol.for('react.element'), // marks it as a genuine React element
type: 'button',
key: null,
props: {
className: 'primary',
children: 'Save',
},
};The fields that matter for this tutorial are these:
typesays what to render. It is either a string such as'button'or a component function or class.propsholds every attribute and thechildren.keyis an optional identity hint. The chapter on keys covers it.
An element is a description of what you want on screen at one moment. Creating one is cheap, because it is only an object allocation. It does not touch the DOM and it does not call your component.
React treats elements as immutable. In development builds React freezes them, so assigning to element.props.className throws an error in strict mode. To change the UI, you return a new element on the next render.
Elements, components, and instances
Beginners often use these three words interchangeably. React keeps them apart.
| Term | What it is | Example |
|---|---|---|
| Component | A function (or class) that takes props and returns elements | `function Greeting(props) { ... }` |
| Element | A plain object describing one thing to render | `<Greeting name="Ada" />` |
| Instance | React's internal record of a mounted component, holding its state | Created by React, never by you |
You write components. A component returns elements. React turns elements into instances and DOM nodes. A single component can have many instances at once. Two <Counter /> elements in the same page share one function but have separate state, because each has its own instance.
Host elements and component elements
The type field splits elements into two groups:
- Host elements have a string type, such as
'div'or'button'. They map to real DOM nodes. - Component elements have a function or class as their type. React must call the component to find out what it returns.
JSX uses capitalization to tell them apart. <div /> compiles to createElement('div'), a string. <Div /> compiles to createElement(Div), a variable reference. This is why a component named greeting fails. React treats <greeting /> as a host element named "greeting" and creates an unknown DOM tag instead of calling your function.
Element trees
Elements nest through props.children. A component's return value is therefore a tree of elements, and React expands component elements by calling them until only host elements remain.
The Greeting element is a leaf of the tree you wrote, but it is not a leaf of the final tree. React calls Greeting({ name: 'Ada' }), receives the h1 element, and continues down the tree. This expansion is the render phase, which a later chapter covers. For now, remember that React calls your component functions. You do not.
What a component can return
A component may return any value React knows how to render:
- A single element, host or component.
- A string or a number, which becomes a text node.
- An array of any renderable values. Each item in the array needs a key.
- A fragment, written
<>...</>, which groups siblings without adding a DOM node. null,undefined,true, orfalse, which render nothing.- A portal created with
createPortal, which renders into a different DOM node.
The next example uses each of the common shapes:
function Page({ user, notices }) {
if (!user) {
return null; // renders nothing
}
return (
<>
<h1>Welcome, {user.name}</h1>
{notices.length > 0 && <p>You have {notices.length} notices.</p>}
<ul>
{notices.map(n => (
<li key={n.id}>{n.text}</li>
))}
</ul>
</>
);
}A plain object that is not an element is not allowed. Writing <p>{{ a: 1 }}</p> throws "Objects are not valid as a React child". Convert the object to a string or to elements first.
Common errors
Two roots without a wrapper. A function returns one value, so return <h1/><p/> is a syntax error. Wrap the siblings in a fragment or return an array.
Rendering 0 by accident. In {count && <Badge />}, a count of 0 makes the expression evaluate to 0. React renders that number as text. Use {count > 0 && <Badge />} instead.
Calling a component as a function. Writing Greeting({ name: 'Ada' }) inside another component runs it immediately. Its hooks then belong to the caller, and React has no separate instance for it. The result breaks when the call is conditional, because hook order changes. Write <Greeting name="Ada" /> and let React call it.
Mutating props or elements. Props belong to the parent's element. Assigning to props.items.push(x) changes data the parent owns and breaks the assumption that rendering is a pure calculation. The next chapter develops that rule.
Defining components inside components. A function declared in the body of another component is a new function on every render. React sees a different type each time and treats it as a different component. It discards the previous instance and its state. Declare components at the top level of the module.
Key points
- JSX compiles to calls that return element objects.
- An element describes UI. A component is a function that produces elements. An instance is React's internal record of a mounted component.
- Element
typeis a string for DOM nodes and a function or class for components, and capitalization in JSX decides which. - A component returns a tree of elements, and React expands component elements until only host elements remain.
- Elements are immutable and cheap to create. Returning a new tree on every render is normal.
Exercise
A teammate writes function ProfileCard() { ... } and renders it as <profileCard />. The page shows an empty unknown tag in the DOM and the component's output never appears. What is happening, and what is the fix?
Show answer
JSX treats a lowercase tag name as a host element. <profileCard /> compiles to createElement('profileCard'), with a string type, so React creates a DOM element named profileCard and never calls the function. The fix is to render <ProfileCard />. The capitalized name compiles to a reference to the function, so React treats it as a component element and calls it.
Exercise
What does this component render when count is 0, and how would you change it so it renders nothing?
function Inbox({ count }) {
return <div>{count && <span>{count} new</span>}</div>;
}
Show answer
It renders <div>0</div>. The expression 0 && <span>...</span> evaluates to 0, and React renders numbers as text. Make the condition a boolean, for example {count > 0 && <span>{count} new</span>}, or use a ternary that returns null.