Sub topic 1
Setting up and writing your first components
This chapter creates the React project and builds the first static pieces of the to-do app. By the end you will have a running dev server, an App component, and a small component tree rendered from plain data. State, events, and forms come in later chapters.
Prerequisites
This chapter assumes you already know:
- JavaScript fundamentals: functions, arrays, objects, destructuring, and spread syntax.
- The array methods
mapandfilter. - Basic HTML forms and elements.
- How to use a terminal, with Node.js (version 18 or later) and npm installed.
You do not need to know React yet. If map still feels unfamiliar, review it first, because JSX relies on it heavily.
Creating the project
Vite is a build tool that serves your code during development and bundles it for production. It starts quickly and is a common way to create a React project today.
npm create vite@latest todo-app -- --template react
cd todo-app
npm install
npm run devThe last command starts a dev server, usually at http://localhost:5173. Open that address and you should see the Vite starter page. Edits you save appear in the browser without a full reload. This is called hot module replacement.
The files that matter for this tutorial are:
| File | Purpose |
|---|---|
| `index.html` | The single HTML page. It contains an empty `<div id="root">`. |
| `src/main.jsx` | The entry point. It tells React where to render. |
| `src/App.jsx` | The top-level component. You will edit this most. |
| `package.json` | Dependencies and scripts such as `dev` and `build`. |
Open src/main.jsx. It looks like this:
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App.jsx";
createRoot(document.getElementById("root")).render(
<StrictMode>
<App />
</StrictMode>
);createRoot attaches React to the #root element. render draws the App component inside it. StrictMode is a development helper. It runs some checks twice, such as rendering each component two times, to expose impure code. It has no effect in production builds.
The starter template also includes src/App.css and src/index.css. You can leave them alone or delete their contents. This tutorial does not depend on any styling.
What a component is
A function component is a JavaScript function that returns a description of some UI. React calls it, takes what it returns, and updates the page to match.
Two rules apply:
- The name must start with a capital letter. React treats
<todo />as an HTML tag and<Todo />as your component. - The function should be pure during rendering. Given the same inputs, it returns the same output and does not change anything outside itself.
Replace the contents of src/App.jsx with this:
export default function App() {
return (
<main>
<h1>To-do</h1>
<p>Nothing to do yet.</p>
</main>
);
}Save the file. The browser updates and shows a heading and a paragraph.
Understanding JSX
The return statement above looks like HTML, but it is JSX. JSX is a syntax extension that lets you write markup inside JavaScript. A compiler (Vite uses one automatically) turns each tag into a plain function call that creates a description of an element. You never write those calls yourself.
JSX differs from HTML in several ways that cause common errors:
- One root element. A component must return a single parent. Wrap siblings in a
<div>, a semantic element like<main>, or a fragment (<>...</>) that adds nothing to the page. - Every tag must close. Write
<input />and<br />, not<input>or<br>. - Attributes use camelCase. Use
classNameinstead ofclass,htmlForinstead offor, andonClickinstead ofonclick. - Braces embed JavaScript. Anything inside
{ }is an expression.
The last point is the most useful. Braces work in text and in attribute values:
export default function App() {
const title = "To-do";
const taskCount = 3;
return (
<main>
<h1>{title}</h1>
<p>You have {taskCount} tasks.</p>
<p>Double that is {taskCount * 2}.</p>
</main>
);
}Braces accept expressions, which produce a value. They do not accept statements such as if or for. To choose between two outputs, use a ternary (condition ? a : b) or &&.
export default function App() {
const taskCount = 0;
return (
<main>
<h1>To-do</h1>
{taskCount === 0 ? <p>Nothing to do yet.</p> : <p>{taskCount} tasks.</p>}
</main>
);
}A style object is passed with double braces. The outer pair enters JavaScript, and the inner pair is the object literal: style={{ color: "gray" }}.
Splitting the UI into components
Real apps are built from small components that are nested like HTML elements. A good starting point is to draw boxes around the parts of the interface and give each box a name.
Each box becomes a function. Components can live in the same file for now. Define them at the top level of the module, never inside another component. A component defined inside another is recreated on every render, and React treats it as a new component each time, which discards its state.
function Header() {
return (
<header>
<h1>To-do</h1>
</header>
);
}
function TodoItem() {
return <li>Buy milk</li>;
}
function TodoList() {
return (
<ul>
<TodoItem />
<TodoItem />
<TodoItem />
</ul>
);
}
export default function App() {
return (
<main>
<Header />
<TodoList />
</main>
);
}This renders, but all three items say "Buy milk". Each TodoItem needs its own data.
Passing data with props
Props are the inputs to a component. You pass them as attributes, and the component receives them as a single object. Destructuring in the parameter list is the usual style.
function TodoItem({ title, done }) {
return (
<li>
{title}
{done ? " (done)" : ""}
</li>
);
}
function TodoList() {
return (
<ul>
<TodoItem title="Buy milk" done={false} />
<TodoItem title="Write chapter" done={true} />
<TodoItem title="Call the bank" done={false} />
</ul>
);
}String props can use quotes. Everything else, including numbers, booleans, arrays, and objects, goes in braces. Props are read-only. A component must never assign to its own props. If data needs to change, it will live in state, which the next chapters cover.
Rendering from data
Hard-coding three items does not scale. Real data is an array, and map turns it into elements. This is where the prerequisite on map pays off.
const initialTodos = [
{ id: 1, title: "Buy milk", done: false },
{ id: 2, title: "Write chapter", done: true },
{ id: 3, title: "Call the bank", done: false },
];
function TodoItem({ title, done }) {
return (
<li>
{title}
{done ? " (done)" : ""}
</li>
);
}
function TodoList({ todos }) {
return (
<ul>
{todos.map((todo) => (
<TodoItem key={todo.id} title={todo.title} done={todo.done} />
))}
</ul>
);
}
export default function App() {
return (
<main>
<h1>To-do</h1>
<TodoList todos={initialTodos} />
</main>
);
}The key prop gives each item a stable identity. React uses it to match items between renders. If you omit it, the console shows a warning. The "Rendering the list with stable keys" chapter explains why it matters. For now, use a unique id from the data and never use the array index.
key is not passed to the component. TodoItem cannot read props.key.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| "Adjacent JSX elements must be wrapped in an enclosing tag" | Two root elements are returned | Wrap them in a parent or a fragment |
| Your component renders as an unknown lowercase tag | The name starts with a lowercase letter | Capitalize it: `TodoItem` |
| Blank page and "X is not defined" in the console | A component was used but not defined or imported | Define it or add the `import` |
| "Objects are not valid as a React child" | An object was placed in braces as content | Render a field such as `{todo.title}` |
| Warning about `class` | HTML attribute names were used | Use `className` and `htmlFor` |
| Warning about unique `key` props | A `map` result has no keys | Add `key={todo.id}` |
Moving components into files
Once the file grows, give each component its own module. Create src/TodoItem.jsx:
export default function TodoItem({ title, done }) {
return (
<li>
{title}
{done ? " (done)" : ""}
</li>
);
}Then import it where it is used:
import TodoItem from "./TodoItem.jsx";A default export is imported without braces and can be given any name. A named export (export function TodoItem) is imported with braces, as in import { TodoItem } from "./TodoItem.jsx". Pick one style and use it consistently. This tutorial uses default exports for components.
Exercise
A teammate writes function todoItem() { return <li>Buy milk</li>; } and uses it as <todoItem />. The page shows an empty unknown element and no text. What is wrong, and how do you fix it?
Show answer
React treats lowercase tags as built-in HTML elements, so <todoItem /> is rendered as an unknown DOM element instead of calling the function. Rename the function to TodoItem and use <TodoItem />.
Exercise
Add a Header component that takes a count prop and shows "You have N tasks." Render it from App using the number of items in initialTodos. Which expression gives the count, and why is count passed as {count} rather than "count"?
Show answer
Use <Header count={initialTodos.length} />. Braces tell JSX to evaluate a JavaScript expression, so the prop receives the number. With quotes, the prop would receive a literal string. The component renders it with <p>You have {count} tasks.</p>.