Sub topic 1
Components as Functions That Return JSX
A React component is a JavaScript function that takes an input and returns a description of what should appear on screen. This chapter covers that model: what a component is, what JSX compiles to, and the rules that make a function a valid component. Later chapters build on it by passing props, the inputs to a component, in more detail.
Prerequisites
This chapter assumes you have the following:
- Basic JavaScript: functions, objects, destructuring, and arrow functions.
- Familiarity with HTML elements and attributes.
- A running React project, for example one created with Vite (
npm create vite@latest, then choose the React template).
You do not need to know hooks or state yet.
The working model
A component is a function. React calls it, and the function returns what React should render. The output is usually JSX, a syntax extension that looks like HTML but lives inside JavaScript.
function Welcome() {
return <h1>Hello, world!</h1>;
}
export default function App() {
return (
<main>
<Welcome />
<Welcome />
</main>
);
}Welcome is defined once and used twice. Each <Welcome /> is a separate instance, so React calls the function once for each instance.
You never call Welcome() yourself. You write <Welcome /> and React decides when to call the function. This matters later, because React may call a component several times as the screen updates.
What JSX compiles to
Browsers cannot run JSX. A build tool such as Vite (through Babel or esbuild) converts each JSX element into a plain function call. With the modern JSX transform, <h1>Hello</h1> becomes roughly this:
import { jsx } from 'react/jsx-runtime';
const element = jsx('h1', { children: 'Hello' });The result is a plain JavaScript object called a React element. It describes what to draw: a type ('h1'), and a set of props (here, children). It is not a real DOM node. React reads these objects, compares them with the previous ones, and updates the real DOM only where something changed.
For your own components, the type is the function itself:
import { jsx } from 'react/jsx-runtime';
function Welcome() {
return jsx('h1', { children: 'Hello, world!' });
}
const element = jsx(Welcome, {});The compiled form shows two facts. First, a component receives one object, which holds its props. Second, JSX is only a way to write these function calls more readably.
Rules for a valid component
A function works as a component when it meets these conditions.
- The name starts with a capital letter. JSX treats lowercase tags as built-in HTML elements and capitalized tags as components.
- It returns something React can render. That means JSX, a string, a number,
null, or an array of these. - It takes at most one parameter. React passes the props object as the first argument.
- It does not define itself inside another component. Details are in the edge cases below.
The capitalization rule is the most common source of confusion:
function greeting() {
return <p>Hi</p>;
}
export default function App() {
// React looks for an HTML tag named "greeting", not your function.
return <greeting />;
}This renders an unknown <greeting> element in the DOM, and the browser shows nothing useful. Rename the function to Greeting and use <Greeting />.
Arrow functions work too
Both function declarations and arrow functions are valid:
const Badge = () => <span className="badge">New</span>;
export default function App() {
return <Badge />;
}Pick one style per project. The behavior is the same.
JSX rules you will meet immediately
JSX is stricter than HTML. These rules cause most first errors.
Return one root element
A function returns one value, so JSX must have a single root. Wrap siblings in a parent element or in a fragment, <>...</>, which adds no extra DOM node.
function Contact() {
return (
<>
<h2>Contact</h2>
<p>[email protected]</p>
</>
);
}Close every tag
Self-closing tags need the slash. <img> is valid HTML, but in JSX you must write <img />. The same applies to <input /> and <br />.
Use camelCase attribute names
Some HTML attribute names are reserved words in JavaScript or follow a different style in the DOM API. JSX uses these names:
| HTML | JSX |
|---|---|
| `class` | `className` |
| `for` | `htmlFor` |
| `onclick` | `onClick` |
| `tabindex` | `tabIndex` |
Put JavaScript inside curly braces
Curly braces switch from JSX back to JavaScript. You can use them for content and for attribute values:
function Clock() {
const now = new Date();
const label = now.toLocaleTimeString();
return <p title={label}>Time: {label}</p>;
}Only expressions go in braces, meaning code that produces a value. Statements such as if and for do not. Use a ternary (condition ? a : b) or && inside JSX, or run an if before the return.
Parenthesize multi-line returns
If the JSX starts on a new line after return, wrap it in parentheses. Without them, automatic semicolon insertion ends the statement after return:
function Broken() {
return
<h1>Never rendered</h1>;
}
function Fixed() {
return (
<h1>Rendered</h1>
);
}Broken returns undefined because JavaScript inserts a semicolon right after return. In React 18 and later, returning undefined from a component is allowed, so you may see an empty render with no error. In React 17 and earlier it throws.
Where the props arrive
A component receives its inputs as a single object. Attributes in JSX become properties on that object:
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
export default function App() {
return <Greeting name="Ada" />;
}React calls Greeting({ name: 'Ada' }). Chapter 2 covers props in depth. For now, notice that a component with no attributes still receives an object, an empty one.
Components are rendered, not called
You compose components by placing them in JSX. Do not call them as plain functions:
function Item() {
return <li>Item</li>;
}
export default function List() {
return (
<ul>
<Item />
{/* Avoid: {Item()} */}
</ul>
);
}React tracks each <Item /> as a separate instance with its own identity. A direct call Item() skips that tracking. It works only while Item uses no hooks. The moment you add useState to Item, the hook runs inside List instead, which breaks the rules of hooks and gives confusing errors.
Components should be pure
React expects a component to be a pure function of its props: given the same props, it returns the same JSX. It should not change variables that exist outside the function while rendering.
let count = 0;
// Impure: each render changes a shared variable
function BadCounter() {
count = count + 1;
return <p>{count}</p>;
}
// Pure: output depends only on props
function GoodCounter({ value }) {
return <p>{value}</p>;
}Purity matters because React may call a component more than once for a single update. In development, Strict Mode deliberately renders every component twice to expose impure code. If BadCounter is rendered once, the screen can show 2 because of the extra call.
Side effects, such as fetching data or changing the document title, belong in event handlers or in useEffect, not in the body of the component.
Edge cases and common errors
Defining a component inside another component
export default function Page() {
// A new function on every render of Page
function Panel() {
return <p>Panel</p>;
}
return <Panel />;
}Every time Page renders, it creates a new Panel function. React compares component types by identity, sees a different function, and discards the old instance. It then mounts a fresh one, which loses any state inside Panel. Define components at the top level of the module.
Returning more than one element
function Wrong() {
return <h1>One</h1><p>Two</p>;
}This is a syntax error. Wrap the elements in a fragment or a parent element.
Rendering objects
You can render strings, numbers, and elements. A plain object is not a valid child:
function Wrong() {
const user = { name: 'Ada' };
return <p>{user}</p>;
}React throws "Objects are not valid as a React child". Render a property instead: {user.name}.
Booleans and null render nothing
true, false, null, and undefined produce no output. This is why {isOpen && <Menu />} works. Be careful with numbers: {items.length && <List />} renders the number 0 when the array is empty. Use {items.length > 0 && <List />}.
Class components
Older code uses classes with a render() method. They still work, but new code uses function components, and the rest of this tutorial covers only those.
Putting it together
This example combines the rules above. It defines small top-level components, uses a fragment, uses camelCase attributes, and keeps each component pure.
function Avatar() {
return <img className="avatar" src="/ada.png" alt="Ada Lovelace" />;
}
function Bio() {
const year = 1815;
return <p>Born in {year}. Wrote the first published program.</p>;
}
export default function Profile() {
return (
<>
<h1>Ada Lovelace</h1>
<Avatar />
<Bio />
</>
);
}Profile returns a tree of React elements. React calls Avatar and Bio as it walks that tree, and it builds the DOM from the result.
Summary
- A component is a function that React calls with a props object and that returns JSX.
- JSX compiles to function calls that produce plain element objects. They are descriptions, not DOM nodes.
- Names must be capitalized, the return value must have one root, and JavaScript goes inside curly braces.
- Render components with
<Name />. Do not call them directly. - Keep components pure and define them at module level.
Exercise
A teammate writes function profileCard() { return <div>Ada</div>; } and uses it as <profileCard />. Nothing useful appears on the page. What is wrong, and what is the fix?
Show answer
JSX treats lowercase tag names as built-in HTML elements, so <profileCard /> renders an unknown DOM element instead of calling the function. Capitalize the function name to ProfileCard and use <ProfileCard />.
Exercise
This component sometimes shows 2 in development when you expect 1. Why, and how do you fix it? let renders = 0; function Counter() { renders = renders + 1; return <p>{renders}</p>; }
Show answer
The component is impure because it changes the outer variable renders during rendering. In development, Strict Mode renders each component twice to expose this kind of bug, so the second call increments the value again. Fix it by making the output depend only on props or state, for example by passing the value in as a prop, and by moving any side effect into an event handler or useEffect.
Exercise
Why does {items.length && <List />} display 0 when items is empty, and what is a safer form?
Show answer
The expression 0 && <List /> evaluates to 0, and React renders the number 0, unlike false or null, which render nothing. Use a boolean condition such as {items.length > 0 && <List />}.