Sub topic 2
Quick review: components, JSX, and props
The rest of this tutorial builds a searchable product table from a mockup. Every step relies on three ideas: function components, JSX, and props. This chapter reviews them with the exact pieces the product table uses.
It assumes you can read modern JavaScript (arrays, objects, arrow functions, destructuring) and basic HTML. It also assumes you have seen a React component before. If you have a project that runs React 18 or later, you can paste the examples straight into it.
Components are functions that return UI
A React component is a JavaScript function that returns a description of what should appear on screen. React calls that function while rendering and turns the result into DOM elements.
function ProductCategoryRow({ category }) {
return (
<tr>
<th colSpan="2">{category}</th>
</tr>
);
}Three rules matter here:
- The name starts with a capital letter. React treats
<ProductCategoryRow />as a component and<tr>as a built-in HTML element. A lowercase name such as<productCategoryRow />is treated as an HTML tag that does not exist. - The function returns the UI. A function that returns nothing renders nothing.
- The function should be pure. For the same props it should return the same output, and it should not change anything outside itself while rendering.
The last rule is what makes the later chapters work. If a component's output depends only on its inputs, you can predict what the screen shows by reading the inputs.
Components are declared at the top level
Define components at the top level of a module, not inside other components. A component defined inside another is a new function on every render. React sees it as a different component type each time and throws away its DOM and state.
JSX is JavaScript with markup syntax
JSX looks like HTML, but a build tool compiles it to ordinary function calls. <th colSpan="2">{category}</th> becomes a call that creates an element object. Because it is JavaScript underneath, JSX is stricter than HTML.
| HTML habit | JSX rule |
|---|---|
| `class="note"` | Use `className="note"`. |
| `colspan="2"` | Use camelCase: `colSpan="2"`. |
| `<input>` with no closing tag | Close it: `<input />`. |
| `style="color: red"` | Pass an object: `style={{ color: 'red' }}`. |
| Several sibling elements at the top | Wrap them in one parent, or in a fragment `<>...</>`. |
| `for="name"` on a label | Use `htmlFor="name"`. |
Curly braces switch back to JavaScript
Inside JSX, curly braces {} let you write any JavaScript expression. An expression is code that produces a value. You can use it for text content or for attribute values.
function PriceTag({ price }) {
return <span title={'Price: ' + price}>{price}</span>;
}You cannot put a statement such as if or for inside the braces. Use a ternary operator or && for conditions, and use map for repetition. Or compute a value before the return.
The double braces in style={{ color: 'red' }} are not special syntax. The outer pair means "JavaScript expression here". The inner pair is an object literal.
Props are the inputs to a component
Props (short for properties) are the values a parent passes to a child. You write them like HTML attributes. The child receives them as one object, which you usually destructure in the parameter list.
function ProductRow({ product }) {
const name = product.stocked ? (
product.name
) : (
<span style={{ color: 'red' }}>{product.name}</span>
);
return (
<tr>
<td>{name}</td>
<td>{product.price}</td>
</tr>
);
}Aent uses it like this:
<ProductRow product={{ category: 'Fruits', price: '$1', stocked: true, name: 'Apple' }} />Here product is the prop name, and the value is any JavaScript value in braces. Props can be strings, numbers, booleans, arrays, objects, and functions. A string literal can skip the braces (category="Fruits"). Everything else needs them.
Props are read-only
A component must never modify its props. Writing product.name = 'x' inside ProductRow changes data owned by the parent, and React will not re-render to show it. If a value needs to change over time, it belongs in state. That distinction gets its own chapter, and the whole design process depends on it.
Passing a function as a prop
Props are not limited to data. A parent can pass a function, and the child calls it. This is how a child reports an event upward, and the later chapters use it for the search box and checkbox.
function SaveButton({ onSave }) {
return <button onClick={onSave}>Save</button>;
}Pass the function itself (onClick={onSave}), not the result of calling it (onClick={onSave()}). The second form runs the function during rendering, and it passes its return value to the button.
Default values and the `children` prop
You can give a destructured prop a default value. It applies only when the prop is undefined.
function Badge({ label, color = 'gray' }) {
return <span style={{ background: color }}>{label}</span>;
}Anything you place between a component's opening and closing tags arrives as a special prop named children.
function Card({ title, children }) {
return (
<section>
<h2>{title}</h2>
{children}
</section>
);
}The product table does not need children, but you will see it often in other code.
Conditional rendering
ProductRow already used one common pattern: choose between two pieces of JSX with a ternary expression. There are two other forms to recognize.
condition && <Element />renders the element when the condition is true. Be careful with numbers.count && <Element />renders a literal0whencountis0. Writecount > 0 && <Element />instead.- Returning
nullfrom a component renders nothing.if (!product) return null;is a valid early exit.
Data flows from parent to child
Props only move in one direction. A parent renders a child and hands it values. The child cannot reach back up and change them. The diagram shows this for the first components in the product table.
Each ProductRow gets its own product. Two instances of the same component do not share anything unless the parent gives them the same value.
A complete runnable example
This file combines everything above. It renders a short table by passing data from a parent to its children. It uses no state. The row-and-key logic is deliberately simple here, because the next chapters cover keys and the full table.
import { createRoot } from 'react-dom/client';
const PRODUCTS = [
{ category: 'Fruits', price: '$1', stocked: true, name: 'Apple' },
{ category: 'Fruits', price: '$2', stocked: false, name: 'Passionfruit' },
{ category: 'Vegetables', price: '$1', stocked: true, name: 'Peas' }
];
function ProductCategoryRow({ category }) {
return (
<tr>
<th colSpan="2">{category}</th>
</tr>
);
}
function ProductRow({ product }) {
const name = product.stocked ? (
product.name
) : (
<span style={{ color: 'red' }}>{product.name}</span>
);
return (
<tr>
<td>{name}</td>
<td>{product.price}</td>
</tr>
);
}
function App() {
return (
<table>
<thead>
<tr>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<ProductCategoryRow category="Fruits" />
<ProductRow product={PRODUCTS[0]} />
<ProductRow product={PRODUCTS[1]} />
<ProductCategoryRow category="Vegetables" />
<ProductRow product={PRODUCTS[2]} />
</tbody>
</table>
);
}
createRoot(document.getElementById('root')).render(<App />);Note the shape of the data. PRODUCTS is a plain array of objects. The components never own it. They receive it and display it.
Common errors
These mistakes account for most beginner-to-intermediate trouble with this material.
| Symptom | Likely cause | Fix |
|---|---|---|
| Console warning about an unknown tag, and nothing renders | Component name starts with a lowercase letter | Capitalize the name. |
| "Adjacent JSX elements must be wrapped" | Two top-level elements in one `return` | Wrap them in a parent element or `<>...</>`. |
| `[object Object]` appears on screen | An object placed in braces as text | Render one of its fields, such as `product.name`. |
| "Objects are not valid as a React child" | Same cause, with a plain object or a `Date` | Convert it to a string or pick a field. |
| `0` appears where nothing should | `count && <Element />` with `count` equal to 0 | Compare explicitly: `count > 0 && ...`. |
| A button action fires on page load | `onClick={handle()}` instead of `onClick={handle}` | Pass the function without calling it. |
| Props are `undefined` in the child | Destructured a name the parent did not pass, or a typo in the prop name | Check that the prop names match on both sides. |
What the next chapters build on
Treat each component as a function of its props: given the same inputs, it produces the same UI. The product table follows from that. You will split the mockup into components that each do one job. Each one receives what it needs through props. Later, when something has to change over time, you will add state in one place and still pass its values down as props.
Exercise
In <ProductRow product={p} />, what is product and what may ProductRow do with it? Name two mistakes that would break this code.
Show answer
product is a prop. It is a named input that the parent passes to ProductRow, and ProductRow receives it in an object it can destructure as { product }. ProductRow may read it and use its fields to decide what to render. It may not modify it. Two mistakes: renaming the component to start with a lowercase letter (React then treats it as an HTML tag), and assigning to a field such as product.name = 'x' (this mutates data the parent owns and does not trigger a re-render).
Exercise
Why does <button onClick={handleSave()}> behave differently from <button onClick={handleSave}>, and which one is correct for a click handler?
Show answer
handleSave() calls the function during rendering and passes its return value to onClick, so the action runs on every render and the button gets no usable handler. handleSave passes the function itself, so React calls it when the click happens. The second form is correct.