React basics 01 · Components
Components, JSX and props
What React is for, the first component line by line, the rules of JSX, props and components in files.
Loading lesson…
React basics 01 · Components
What React is for, the first component line by line, the rules of JSX, props and components in files.
Loading lesson…
From the JavaScript chapter you know how to work with data: arrays, objects and functions. But a web page doesn't just compute data – it also has to show it, and after every change show it again, correctly. And that's where the trouble starts. Let's see it on a perfectly ordinary page: a task list with a heading that shows how many tasks there are.
Without React, you change a page by giving the browser commands: "find this element, rewrite its text, insert a new row". The browser offers the document object for that – the whole page, which JavaScript can reach into. Adding a task then looks like this:
// The page's data: an array of tasksconst tasks = ['Shopping', 'Cleaning']// Find the three places on the page that show the tasks.// getElementById('heading') = find the element that has id="heading" in the HTMLconst heading = document.getElementById('heading') // the heading "Tasks (2)"const list = document.getElementById('list') // the <ul> list of tasksconst empty = document.getElementById('empty') // the text "Nothing here"function addTask(label) {tasks.push(label) // 1. change the dataconst li = document.createElement('li') // 2. make a new list row,li.textContent = label // give it textlist.append(li) // and insert it into the listheading.textContent = `Tasks (${tasks.length})` // 3. rewrite the count in the headingempty.hidden = true // 4. hide "Nothing here"}// addTask is called by the "Add" button (id="add") after a click:document.getElementById('add').addEventListener('click', () => addTask('Walk the dog'))
One change of data, four changes to the page. And that's just adding. Deleting a task needs four other steps: find the right row, remove it, rewrite the count and maybe show "Nothing here" again. Renaming needs more. Forget one step and the page lies: the heading says "Tasks (3)", but you see two.
The more places on the page show the same data (the count in the heading, the number on an icon, a summary at the bottom), the more steps you must take after every change and the easier it is to forget one. In a bigger app everyone gets lost in it.
React turns this around. You don't write steps saying "what to change on the page"; you describe once how the page should look for the given data. That description is an ordinary function:
// The function gets the array of tasks and returns how the page should look.// The HTML-like notation inside JavaScript is called JSX – section 2 explains it.function TaskPage({ tasks }: { tasks: string[] }) {return (<section>{/* the count is taken from the data – it can never differ from reality */}<h1>Tasks ({tasks.length})</h1>{/* "Nothing here" only when the array is empty (conditions: the next lesson) */}{tasks.length === 0 && <p>Nothing here</p>}{/* one list row for every task (lists: the next lesson) */}<ul>{tasks.map((task) => <li key={task}>{task}</li>)}</ul></section>)}
No "find", "insert", "rewrite". When a task is added, the function gets a longer array and returns a new description. React compares it with what's on the page now and makes only the changes that are needed by itself – it adds one row and rewrites the number. You never touch the four steps from the manual version, so you can't forget any of them.
This approach is called declarative: you describe the result, not the steps. The manual version above is imperative – it gives orders step by step. (How data changes after a click is the topic of React basics 03, on state. For now it's enough to know that for different data the function returns a different description.)
React is a library for building user interfaces – what the user sees on the page and clicks on. It pays off where the page changes while it's open. The table shows a few typical pages; on the right is whether React suits them and why:
| Page | Does it change while you have it open? | React? |
|---|---|---|
| an online shop with a cart and filters | yes – the cart, counts, filtered goods | ✅ yes |
| a chat, an e-mail inbox | yes – new messages, the unread count | ✅ yes |
| an overview with charts and tables (a dashboard) | yes – data, sorting, switching | ✅ yes |
| this course | yes – the editor, checks, progress, quizzes | ✅ yes |
| a blog post, a company business card | hardly – the text is just read | ❌ HTML and CSS are enough |
| one "Back to top" button on an otherwise finished page | just one small thing | ❌ a few lines of JavaScript are enough |
A simple rule: the more things on the page depend on data that changes, the more work React saves you. For a static page it's needlessly big.
The whole course uses one comparison. Picture a restaurant. A guest doesn't order by steps ("heat the pan, put butter on it, crack two eggs…"). They say what they want: "a ham omelette". How it's made is the kitchen's business.
And two rules of every good kitchen that you'll see in the code: the same order always makes the same dish, and the cook doesn't rewrite the order – they can't change what the guest ordered.
React runs in the browser: the browser downloads the app's JavaScript and React builds the page from it. In this course you don't need to install anything – the demos and challenges run in an editor right on the page. In a real project, though, you'll see a folder that looks roughly like this:
my-app/├─ index.html ← the only HTML page; it contains an empty <div id="root">├─ package.json ← the list of libraries the project uses (react, react-dom…)└─ src/├─ main.tsx ← the start: tells React which element of the page to render the app into├─ App.tsx ← the main component the whole app grows from└─ components/├─ Welcome.tsx ← more components, usually each in its own file└─ TaskList.tsx
The Vite tool creates such a folder with one command (npm create vite@latest; npm is a program that downloads libraries and runs the project's commands). The files end in .tsx: TypeScript (ts) with JSX (x). You know types from lesson TypeScript 01, splitting code into files from lesson JavaScript 08. Section 4 shows how component files talk to each other.
Every component has the same shape. You'll first see it as a template with blanks and right after that the same template filled in with a real greeting.
// ① THE DEFINITION (the recipe) – you write it once, usually in its own file.// A component is an ordinary function. Its name MUST start with a capital letter.function MyComponent({ firstProp, secondProp }: { firstProp: string; secondProp: number }) {// ─── 1. WHAT I GET FROM OUTSIDE (props) ─────────────────// In the function's parentheses: the details that come from the order.// After the colon is their type (lesson TypeScript 01).// ─── 2. WHAT I CALCULATE (ordinary JavaScript) ──────────const something = firstProp.toUpperCase() // anything you're going to show// ─── 3. HOW IT LOOKS (JSX) ──────────────────────────────// The function returns a description of a piece of the page. Values from// JavaScript go inside curly braces { }.return (<div>{something} – {secondProp}</div>)}// ② THE USE (the order) – in the JSX of ANOTHER component, written like an HTML tag.// The attributes on the tag become props.<MyComponent firstProp="hello" secondProp={3} />
The template has three parts, and each comes with one question. Ask them before you start writing a component:
Welcome, ProductCard, TaskList.We want a card saying "Hello, Anna! Good morning". The answers to the three questions: it's called Welcome; from outside it needs a name and whether it's morning (those differ between uses); it looks like a frame with a heading and one line of text.
// ① THE DEFINITION – the file Welcome.tsx// 1. WHAT I GET: name (text) and morning (true/false)function Welcome({ name, morning }: { name: string; morning: boolean }) {// 2. WHAT I CALCULATE: a ternary (lesson JavaScript 06) picks one of two textsconst greeting = morning ? 'Good morning' : 'Good afternoon'// 3. HOW IT LOOKS: a frame with a heading and the greetingreturn (<section className="card"> {/* className = a CSS class, the class attribute of HTML (section 2) */}<h3>Hello, {name}!</h3> {/* {name} → the variable's value goes here, say Anna */}<p>{greeting}</p></section>)}
The definition on its own shows nothing – it's just a recipe in a drawer. The component has to be used: in the JSX of another component you write it as a tag. Here the main component App uses it twice:
// ② THE USE – the file App.tsxfunction App() {return (<main>{/* One recipe, two orders → two cards */}<Welcome name="Anna" morning={true} /><Welcome name="Peter" morning={false} /></main>)}
All that's left is telling React where to cook the whole app. A single line in the file main.tsx does that:
// the file main.tsx – the start of the appimport { createRoot } from 'react-dom/client' // React's function for the browser// 1. document.getElementById('root') finds the empty <div id="root"> in index.html// 2. createRoot(…) turns it into the place where React will draw// 3. .render(<App />) renders the main component there – and with it everything it containscreateRoot(document.getElementById('root')!).render(<App />)// The exclamation mark after the parenthesis tells TypeScript: "that element is surely there, it won't be null" (lesson TypeScript 02).
What happens when the page loads:
App. It returns a description: "main, with Welcome twice inside".<Welcome name="Anna" morning={true} />. It collects the attributes into the object { name: 'Anna', morning: true } and calls the function Welcome with it.Welcome calculates greeting = "Good morning" and returns the description of the card.<div id="root">. When something changes later, it calls the functions again and changes on the page only what differs.The whole comparison in one place. The table reads by rows: the kitchen on the left, React in the middle, code on the right:
| In the kitchen | In React | In code |
|---|---|---|
| a recipe | a component | function Welcome() { … } |
| an order | props | <Welcome name="Anna" /> |
| the finished dish | JSX – a description of the result | return <h3>Hello, {name}!</h3> |
| the cook | React | createRoot(…).render(<App />) |
| a menu made of dishes | the component tree | App → Welcome, Welcome |
What you see: Two cards rendered by the same component Welcome. The left one gets its order from the fields, the right one has a fixed order (Peter, afternoon). Above them you see what the left card's order would look like in code.
Try it:
Welcome is an ordinary function that returns JSX. The fields at the top use state – React basics 03 explains it.The takeaway: A component describes how the result should look for a given order. The cooking – including cooking again after every change – is React's job.
Loading the interactive part…
From the first letter React tells whether it's your component or an HTML tag. <section> with a small letter is a browser tag, <Welcome> with a capital one is a component.
| Written as | What React thinks | Result |
|---|---|---|
<Welcome name="Anna" /> | the component Welcome | ✅ calls your function |
<welcome name="Anna" /> | an unknown HTML tag "welcome" | ❌ the function isn’t called, nothing on the page |
JSX looks like HTML, but it's JavaScript. Before the code runs, a tool (Vite, say) translates every tag into an ordinary function call that makes an object describing the element:
// You write this:<h3 className="title">Hello, {name}!</h3>// This is what it becomes (simplified):jsx('h3', { className: 'title', children: ['Hello, ', name, '!'] })// → the object { type: 'h3', props: { className: 'title', children: [...] } }
You don't need to remember that. But it explains all the rules of JSX: why there must be only one root element (a function returns one value), why attributes have JavaScript names (they're properties of an object) and why if can't go inside curly braces. Let's go through them one at a time, always "not like this / like this".
Inside { } there can be any expression – a piece of code that has a value: a variable, a calculation, a function call, a ternary. A statement (if, for, const) has no value – it does something – so it can't go inside the braces. It belongs above the return.
// ✅ expressions – all have a value<p>{name}</p> // a variable → Anna<p>${price * count}</p> // a calculation → $36<p>{name.toUpperCase()}</p> // a function call → ANNA<p>{morning ? 'Good morning' : 'Good afternoon'}</p> // a ternary → one of the texts// ❌ a statement – if has no value, JSX can't insert it<p>{if (morning) { 'Good morning' }}</p> // an error when translating// ✅ the statement goes above return, into JSX you put only the resultconst greeting = morning ? 'Good morning' : 'Good afternoon'return <p>{greeting}</p>
The same window applies to attributes: quotes mean "this is text", curly braces "this is JavaScript".
<img src="logo.png" /> // text: the path to the image<img src={user.photo} /> // JavaScript: the value from a variable<input maxLength={20} /> // JavaScript: the number 20 (in quotes it would be the text "20")
A function returns one value, so JSX must have one outer wrapper. When you don't want any wrapping <div> (it might break the page layout, say), use a fragment <>…</>: a wrapper that doesn't appear on the page.
// ❌ two siblings side by side – a function can't return two thingsreturn (<h3>Heading</h3><p>Text</p>)// ✅ a fragment – the page will have just <h3> and <p>return (<><h3>Heading</h3><p>Text</p></>)
In HTML you may write <br> or <img src="…"> without closing them. In JSX every tag is closed – either with a pair <p>…</p>, or with a slash at the end: <br />, <img src="logo.png" />, <input />. The slash at the end also suits components without content: <Welcome name="Anna" morning /> (a bare morning without an equals sign is short for morning={true} – more in section 3).
Attributes become properties of an object, so they're named as in JavaScript. The table shows the ones you'll meet straight away; HTML on the left, JSX in the middle, the reason on the right:
| In HTML | In JSX | Why |
|---|---|---|
class="card" | className="card" | JavaScript has the word class taken |
<label for="email"> | <label htmlFor="email"> | for is a JavaScript word too (a loop); the attribute links a label with a field |
onclick="…" | onClick={…} | events are written in camelCase (every next word with a capital letter) and get a function – React basics 03 |
style="color: red" | style={{ color: 'red' }} | a style is an object; properties in camelCase: fontSize instead of font-size |
The double braces in style are nothing new: the outer { } is the window into JavaScript, the inner { } is an object (lesson JavaScript 03).
Inside JSX neither <!-- --> from HTML nor // works. A comment is written {/* like this */} – a window into JavaScript that holds only a comment.
What for: props let you use one component in several places with different details. Without props, Welcome could greet only Anna, and for Peter you'd write a second, almost identical function.
How: props are the function's argument. React collects all the attributes you write on the component's tag into one object and passes it to the function as its first parameter.
When: a simple rule – whatever differs between the uses of a component is a prop. Whatever is always the same goes straight into the component.
Code with props always has two parts in two different places: ① the recipe – the component's definition, and ② the order – the place where you use it. The recipe first. This time we describe the order's shape separately with interface (lesson TypeScript 01) – with more props it's clearer than everything on one line:
// ① THE RECIPE – the file ProfileCard.tsx// The order's shape: which props the component acceptsinterface ProfileCardProps {name: string // required: the namerole?: string // question mark = optional: the roleavatar?: string // optional: an emoji instead of a photo}// ↓ React puts the object with the attributes from ② herefunction ProfileCard({ name, role = 'Developer', avatar = '🙂' }: ProfileCardProps) {// ↑ default values: used when the attribute is missingreturn (<div className="card"><span>{avatar}</span><strong>{name}</strong><div>{role}</div></div>)}
And the order – the component App wants two cards, so it writes the tag twice with different attributes:
// ② THE ORDER – the file App.tsxfunction App() {return (<div className="row"><ProfileCard name="Anna Smith" role="Frontend" avatar="👩💻" /><ProfileCard name="Peter Brown" /></div>)}
What travels from the order into the recipe. The table reads by rows: the attribute on the tag on the left, the variable's value for Anna in the middle, for Peter – who got neither role nor avatar – on the right:
| Attribute on the tag ② | Variable in ① for Anna | For Peter |
|---|---|---|
name | 'Anna Smith' | 'Peter Brown' |
role | 'Frontend' | 'Developer' (the default value) |
avatar | '👩💻' | '🙂' (the default value) |
A prop can be anything JavaScript can do: text, a number, true/false, an array, an object, even a function. By rule 2 from section 2 only text goes in quotes. The table shows how each value is written:
| Value | Written on the tag | What the component gets |
|---|---|---|
| text | title="News" | 'News' |
| a number | price={120} | 120 |
| true / false | morning={false} | false |
| true – shorthand | morning (without an equals sign) | true |
| a variable | name={userName} | the variable’s value |
| an array | tags={['new', 'sale']} | ['new', 'sale'] |
| an object | user={{ name: 'Anna' }} | { name: 'Anna' } |
| a function | onSave={save} | a function it can call (React basics 04) |
| ❌ Not like this | ✅ Like this |
|---|---|
<Price amount="120" /> – the component gets the text "120". The calculation amount + 1 then gives "1201" (the text is joined, lessonJavaScript 01). | <Price amount={120} /> – the component gets the number 120 and amount + 1 is 121. TypeScript warns you about the mistake when the type says amount: number. |
The cook doesn't rewrite the guest's order. A component never changes its props – it only reads them and calculates from them:
function ProfileCard(props: ProfileCardProps) {props.name = props.name.toUpperCase() // ❌ changes an order that isn't its ownconst shownName = props.name.toUpperCase() // ✅ calculates a new value into its own variablereturn <strong>{shownName}</strong>}
Why? The props object belongs to whoever used the component. If the component rewrote it, whoever used it would suddenly have different data than they think, and React wouldn't know it should redraw anything. Above all, "the same order = the same dish" would stop being true. When something on the screen should change (after a click, say), you need state – the topic of React basics 03.
Props always go one way: from the component that wrote the tag (the parent) to the component that got it (the child). App is the parent of both cards; the cards don't know about each other and return nothing to App. When a child needs to tell its parent something ("I was clicked"), the parent sends it a function in props – React basics 04 shows that.
In the examples the components were together; in a real project most of them have their own file (Welcome.tsx, TaskList.tsx). The files talk to each other through export and import – just like the modules from lesson JavaScript 08:
// the file src/components/Welcome.tsx// export = "other files may use this function too"export function Welcome({ name }: { name: string }) {return <h3>Hello, {name}!</h3>}
// the file src/App.tsx// import = "take Welcome from the file components/Welcome.tsx"// ./ = the folder this file is in; the .tsx extension isn't writtenimport { Welcome } from './components/Welcome'export function App() {return <Welcome name="Anna" />}
A function without export is private: only the file it's in can use it. That suits small helper components that make no sense elsewhere. (You'll also see export default – the file then has one main thing and is imported without curly braces: import App from './App'. Both work equally well.)
At first you often end up with one big component holding everything. A simple rule for when to take a piece out into its own component – one of these is enough:
The task page from the lesson's introduction could be split like this – every line is one component, the indentation shows what's inside what:
App ← the whole page├─ Header ← the heading "Tasks (2)"├─ TaskList ← the list│ ├─ TaskRow ← one row (repeats for every task)│ └─ TaskRow└─ Footer ← the footer
This picture is called the component tree: App at the top, its children below it, their children below them. Props flow down the tree from top to bottom.
This section is for later – come back to it when you write your own component. You'll find the same pattern in the Cheat sheets on the React tab.
// the file src/components/ProductCard.tsx// 1. WHAT IT NEEDS FROM OUTSIDE – the order's shapeinterface ProductCardProps {name: string // a required propprice: numberunit?: string // an optional prop (question mark)}// 2. WHAT IT'S CALLED – a capital letter, export so other files can see itexport function ProductCard({ name, price, unit = 'pc' }: ProductCardProps) {// 3. WHAT IT CALCULATES – ordinary JavaScript, it only reads the propsconst shownPrice = `$${price} / ${unit}`// 4. HOW IT LOOKS – one root element, values in { }return (<div className="card"><strong>{name}</strong><div>{shownPrice}</div></div>)}// USE – in the parent:// import { ProductCard } from './components/ProductCard'// <ProductCard name="Apple" price={2} />// <ProductCard name="Flour" price={3} unit="kg" />
The table is an index of the most common wishes; what you want on the left, the code in the middle, the section with the explanation on the right:
| I want… | Code | Section |
|---|---|---|
| to show a value from a variable or a prop | <p>{name}</p> | 2 |
| to return two elements without a wrapper | <>…</> | 2 |
| a class or a style | className="card" style={{ color: 'red' }} | 2 |
| to pass a component a text | <Badge name="Anna" /> | 3 |
| to pass a component a number or true/false | <Price amount={120} sale /> | 3 |
| an optional prop with a default value | { role = 'Developer' }: Props | 3 |
| to use a component from another file | import { Card } from './Card' | 4 |
A wrapper for someone else's content, conditions and lists are added to the template by the next lesson, React basics 02.
<>…</>).<img />, <input />).The component already gets its props, it just doesn't show them yet. Two places in the JSX to put a value in curly braces.
Task is in the comments in the code below – at the top of the file and at the places marked TODO.
row, stack, card, list, btn, input or muted are the course's ready-made styles in src/styles.css (row = side by side, stack = stacked, card = bordered box, muted = grey text).Loading the interactive part…
The challenge practises sections 1 to 3: you'll write a product card that the page uses several times with different details. For the component, first tell yourself: what it's called, what it needs from outside and how it looks – you'll find the template in sections 1 and 5.
One component, three cards with different details. What should show is in the comments in the code.
Task is in the comments in the code below – at the top of the file and at the places marked TODO.
row, stack, card, list, btn, input or muted are the course's ready-made styles in src/styles.css (row = side by side, stack = stacked, card = bordered box, muted = grey text).Loading the interactive part…
{ } (expressions only), one root element, every tag closed, className instead of class.export and import. Move a piece of the page out when it repeats, has its own name, or the function is too long.