Appearance
6.4.1 — React from Zero: Components, JSX and Props
A product page has forty product cards. Each one shows a name, a price and an "Add to cart" button. The shop owner asks you to make the button grey when an item is sold out.
With plain HTML and JavaScript, you would change forty places. With React, you change one place, because the card is written once and used forty times.
That is the whole idea of React: build the page out of small, reusable pieces called components, and describe what each piece should look like for the data it is given. This page teaches the three things everything else rests on: components, JSX and props.
1. The problem React solves
Start with what you already know. Here is a cart badge written with plain JavaScript, the way Chapter 6.3 taught it:
js
const badge = document.getElementById('cart-count');
function addToCart() {
count = count + 1;
badge.textContent = String(count); // you must update the screen yourself
}You changed the number, and then you had to find the badge and change it too. That sounds fine for one badge. Now picture a page with a badge in the header, a total in the sidebar, a "your cart is empty" message, a checkout button that is disabled when the cart is empty, and a free-shipping banner that appears above a certain amount. Every time the cart changes, you must remember to update all of them, and forget one and the page lies to the user. This is where bugs breed.
React changes the job. You stop writing "when this happens, update that". Instead, you write what the page should look like for the current data, and React makes the screen match.
The screen is a function of the data. Give React the data, and your code answers "what should be on screen?". React does the updating.
Everything on this page and the next two follows from that one sentence.
2. Setting up a project
React is a library you add to a web page. To use it properly you need a tool that bundles your files and gives you a development server that refreshes on save. The most common choice today is Vite (Chapter 6.6 explains what a bundler does).
bash
npm create vite@latest shop -- --template react-ts
cd shop
npm install
npm run devreact-ts means React with TypeScript. The last command starts a server and prints a local address, usually http://localhost:5173. Open it and you see the starter page. Now look at the files Vite made:
text
shop/
index.html the one real HTML page: it holds an empty <div id="root">
src/
main.tsx the entry point: starts React
App.tsx your first componentindex.html has a single empty box, <div id="root"></div>. React will fill that box. All the other files are JavaScript and TypeScript. The x in .tsx means "this file contains JSX", which you meet in a moment.
Here is src/main.tsx, the whole startup of a React app:
tsx
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import App from './App'
createRoot(document.getElementById('root')!).render( // (1)
<StrictMode> {/* (2) */}
<App /> {/* (3) */}
</StrictMode>,
)document.getElementById('root')finds the empty box inindex.html. The!at the end tells TypeScript "I promise this is notnull".createRoottells React "this box is yours"..render(...)says "draw this inside it".StrictModeis a helper that checks your code for mistakes while you develop. It does nothing in the finished site. Chapter 6.4.5 explains what it does and why.<App />is your top component. Everything on the page lives inside it.
That is the entire connection between the browser and React. From here on you work inside App and the components it uses.
3. Your first component
A component is a function that returns a piece of the screen. That is all.
tsx
function Greeting() {
return <h1>Welcome to the shop</h1>
}Greeting is a normal JavaScript function. It takes nothing and returns something that looks like HTML. You use it by writing it like an HTML tag:
tsx
function App() {
return (
<div>
<Greeting />
<Greeting />
</div>
)
}This draws the heading twice. <Greeting /> means "call the Greeting function here and put what it returns in this spot". Write the function once, use it as often as you like.
There are three rules to know from day one.
Rule one: a component name starts with a capital letter. Greeting is a component. greeting is not. React uses the first letter to decide what you meant: <div> with a small d means the HTML tag, and <Greeting /> with a capital means your function. If you write <greeting />, React treats it as an HTML tag called "greeting", which does not exist, and shows nothing useful.
Rule two: a component returns one thing. You cannot return two sibling elements side by side:
tsx
function Broken() {
return (
<h1>Shop</h1>
<p>Welcome</p> // error: adjacent elements must be wrapped
)
}The error message reads "Adjacent JSX elements must be wrapped in an enclosing tag". The fix is to wrap them in one parent. If you do not want an extra <div> in the page, use an empty wrapper called a fragment, written <> and </>. It groups elements and leaves no trace in the HTML:
tsx
function Fixed() {
return (
<>
<h1>Shop</h1>
<p>Welcome</p>
</>
)
}Rule three: wrap a multi-line return in parentheses. In JavaScript, a line that says only return followed by a new line returns nothing, because the language ends the statement there. The parentheses prevent that. Most editors add them for you.
4. JSX: HTML-looking code inside JavaScript
The tag-like text you have been writing is called JSX. It is not HTML, and it is not a string. It is a special syntax that looks like HTML so that building a screen reads naturally.
Browsers cannot run JSX. Before your code reaches the browser, the build tool (Vite does this for you) rewrites each tag into an ordinary function call:
js
// You write:
<h1 className="title">Welcome to the shop</h1>
// The tool turns it into (simplified):
jsx("h1", { className: "title", children: "Welcome to the shop" })That function call returns a plain JavaScript object that describes the element: its type ("h1"), and its properties. Chapter 6.4.4 shows exactly what those objects are and how React uses them. The point for now is that JSX is only a more comfortable way to write function calls. There is no magic.
Putting values into JSX: curly braces
Anything inside { } is JavaScript. This is how data gets onto the screen:
tsx
function Receipt() {
const customer = 'Ana'
const priceCents = 1999
return (
<p>
Thank you, {customer}. Total: ${(priceCents / 100).toFixed(2)}
</p>
)
}This draws: Thank you, Ana. Total: $19.99.
Look at ${(priceCents / 100).toFixed(2)}. The $ is just the dollar sign character in the text. The { ... } after it is a JavaScript expression that works out 19.99. It looks like a template string from Chapter 3.6.7, but it is not one. You are free to put any expression in the braces: a variable, arithmetic, a function call, a ternary (a ? b : c). You cannot put a statement like if or for there, because braces hold a value, and a statement does not produce one. (The next page shows the replacements.)
You can also use braces for attributes:
tsx
<img src={product.imageUrl} alt={product.name} />
<button disabled={!product.inStock}>Add</button>When the value is a plain text string you can use quotes (alt="Red mug"). When it is anything else, or computed, use braces.
The differences from HTML
JSX is stricter than HTML, and a few attributes have different names, because JSX attributes become JavaScript property names.
| In HTML | In JSX | Why |
|---|---|---|
class="card" | className="card" | class is a reserved word in JavaScript |
for="email" | htmlFor="email" | for is a reserved word too |
onclick="go()" | onClick={go} | Names are camelCase, and you pass a function, not a string |
style="color: red" | style={{ color: 'red' }} | style takes an object |
<br> | <br /> | Every tag must be closed |
tabindex="0" | tabIndex={0} | camelCase |
The style={{ color: 'red' }} has two pairs of braces, and it confuses everyone once. The outer pair means "here comes JavaScript". The inner pair is the JavaScript object { color: 'red' }. So double braces are not special syntax, just an object inside the braces. Inside it, CSS names become camelCase: font-size is fontSize, and numbers mean pixels.
More small rules:
tsx
<>
{/* a comment in JSX looks like this */}
<input type="checkbox" checked /> {/* true is written as just the name */}
<Greeting {...props} /> {/* spread: pass many props at once */}
</>Why JSX is safe
When you put a value in braces, React escapes it. If a customer types <script>alert('hacked')</script> as their name, React shows that text literally and does not run it. So the cross-site scripting attack from Chapter 8.5 does not work through normal JSX. The one way to switch the protection off is a property with a deliberately scary name, dangerouslySetInnerHTML. If you ever see it, treat it as a warning sign.
5. Props: giving a component its data
A Greeting that always says the same words is not very useful. A component becomes powerful when it takes input and produces output for that input. The input is called props (short for properties).
Think of a component as a function, because it is one. A normal function takes arguments: total(prices). A component takes one argument, an object of props: ProductCard({ product }).
Here is the card from the start of this page:
tsx
type Product = {
id: string
name: string
priceCents: number
inStock: boolean
}
type ProductCardProps = { // (1)
product: Product
onAdd: (id: string) => void
highlight?: boolean
}
function ProductCard({ product, onAdd, highlight = false }: ProductCardProps) { // (2)
return (
<article className={highlight ? 'card card--hot' : 'card'}> {/* (3) */}
<h2>{product.name}</h2>
<p>${(product.priceCents / 100).toFixed(2)}</p>
<button disabled={!product.inStock} onClick={() => onAdd(product.id)}> {/* (4) */}
{product.inStock ? 'Add to cart' : 'Sold out'} {/* (5) */}
</button>
</article>
)
}Read it line by line.
ProductCardPropsis a TypeScript type that lists exactly what this component accepts.productis required.onAddis a function that takes a product id and returns nothing.highlight?has a question mark, so it is optional. TypeScript will now warn you if you forgetproduct, pass a number where text is expected, or misspell a prop name. This is one of the biggest reasons to use TypeScript with React.- The function takes one parameter, the props object, and takes it apart in the same breath:
{ product, onAdd, highlight = false }is destructuring (Chapter 3.6). The= falsegiveshighlighta default value for when the caller leaves it out. - The class name depends on a prop. This is the screen as a function of data, in one line.
onClick={() => onAdd(product.id)}: when the button is clicked, call the function that was passed in, with this product's id. The card does not know what "add to cart" means. It only knows to callonAdd. That separation is deliberate, and the next page builds on it.- A ternary chooses the button's label from
product.inStock.
Now use the card. The parent passes props by writing them like HTML attributes:
tsx
const mug: Product = { id: 'p1', name: 'Red mug', priceCents: 1999, inStock: true }
const lamp: Product = { id: 'p2', name: 'Desk lamp', priceCents: 4500, inStock: false }
function App() {
function handleAdd(id: string) {
console.log('Add to cart:', id)
}
return (
<main>
<ProductCard product={mug} onAdd={handleAdd} highlight />
<ProductCard product={lamp} onAdd={handleAdd} />
</main>
)
}product={mug} hands the mug object to the first card. highlight with no value means highlight={true}. The second card leaves highlight out, so it gets the default, false. The lamp is out of stock, so its button is disabled and says "Sold out". Click the mug's button, and the console prints Add to cart: p1.
Two cards, one function, two different results. And if the shop owner wants the sold-out button grey, you change ProductCard once.
Props flow down, never up
Here is the picture to keep in your head. A React screen is a tree of components. The parent hands props down to its children, and the children hand them down to theirs.
Data moves in one direction: from parent to child. A child cannot reach up and change what its parent gave it. If a child needs to tell its parent something, like "the user clicked Add", the parent passes down a function (here onAdd), and the child calls it. The data still flows down. Only the notification goes up, through a function that the parent wrote.
This one-way flow is the reason React programs are easy to follow. To find out where a value came from, you walk up the tree until you find who passed it.
Props are read-only
A component must never change its props:
tsx
function BadCard({ product }: { product: Product }) {
product.name = product.name.toUpperCase() // wrong: changes the parent's object
return <h2>{product.name}</h2>
}The product object belongs to the parent. If the card changes it, other components that use the same object suddenly see different data, and React cannot tell anything changed, so the screen can show a mix of old and new. The correct way is to compute a new value and leave the original alone:
tsx
function GoodCard({ product }: { product: Product }) {
const title = product.name.toUpperCase() // a new string; the original is untouched
return <h2>{title}</h2>
}This leads to a rule that React depends on, and you will see it again many times: a component should be pure. Given the same props, it returns the same result, and it changes nothing outside itself while it runs. Chapter 6.4.4 explains why React needs this and what breaks without it.
Children: putting things inside a component
Sometimes you want to wrap content, as you would wrap text in a <div>. The special prop children holds whatever is written between a component's opening and closing tags.
tsx
import type { ReactNode } from 'react'
function Panel({ title, children }: { title: string; children: ReactNode }) {
return (
<section className="panel">
<h2>{title}</h2>
{children}
</section>
)
}
function App() {
return (
<Panel title="Today's deals">
<p>Free shipping over $50.</p>
<ProductCard product={mug} onAdd={() => {}} />
</Panel>
)
}Panel draws a box with a title and puts whatever you placed inside it where {children} is. ReactNode is the TypeScript type for "anything React can draw": text, numbers, elements, arrays of them, or nothing. The panel does not need to know what is inside. That is how page layouts, cards, modals and menus are built in React.
6. How a screen becomes a tree
To close the loop, here is the full path from your code to pixels.
- You write components in JSX.
- A build tool turns each JSX tag into a function call.
- When React runs your component, those calls return small element objects that describe the screen.
- React compares the description with what is already on the page, and changes only what differs.
- The browser shows the result.
You write the first step. React does the rest. When data changes, steps 3 to 5 run again, and you never touch the page yourself. The next page shows how data changes.
7. Organising your files
You will end up with many components, and there are conventions that every React codebase follows, so that anyone can find things.
- One component per file, and the file has the same name as the component:
ProductCard.tsx. Components use PascalCase (capital first letter in every word). - Export the component so other files can import it. Many teams use a named export (
export function ProductCard) because it keeps the name the same everywhere and lets the editor rename it safely. Others useexport default. Pick one and stay consistent. - Group by feature, not by type. A folder
features/cart/holdingCartBadge.tsx,CartList.tsxandcart.tsis easier to work in than one giantcomponents/folder with two hundred unrelated files. - Keep components small. If a component has more than one clear job, or grows past a screenful, split it. A good test: can you describe it in one sentence without using the word "and"?
tsx
// src/features/products/ProductCard.tsx
export function ProductCard(/* … */) {
/* … */
}tsx
// src/App.tsx
import { ProductCard } from './features/products/ProductCard'8. The five mistakes everyone makes
classinstead ofclassName. React shows a warning, "Invalid DOM propertyclass. Did you meanclassName?", but the page often still works. Fix it anyway.- A lowercase component name.
<productCard />is treated as an HTML tag, not your function. - Two siblings with no wrapper. Use a parent element or a fragment.
- Writing
onClick={handleClick()}with the brackets. That calls the function while drawing the page, and passes its result to the button. WriteonClick={handleClick}, oronClick={() => handleClick(id)}when you need to pass something. The next page covers this in detail. - Changing props. Compute a new value instead.
What the interviewer will push on
React fundamentals appear in nearly every front-end interview, usually as short, quick questions. They are an easy place to look either solid or shaky.
"What is JSX?" A syntax that looks like HTML and is written inside JavaScript. It is not understood by the browser. A build tool turns each tag into a function call that returns an object describing an element. The tell of a strong answer: saying it is only syntax sugar for function calls, not a template language and not HTML.
"What is a component?" A function (or, in older code, a class) that takes props and returns a description of part of the screen. Add that it should be pure: same props, same output, no changing things outside itself.
"What are props? Can a component change them?" Props are the inputs a parent passes to a child. No: they are read-only, and a child that needs to change something calls a function the parent passed down.
"What is the difference between props and state?" Props come from outside and are read-only. State belongs to the component and can change over time. (The next page covers state.) A one-line answer: props are arguments, state is memory.
"Why do you need a key in a list?" React uses the key to match last render's items with this render's items, so each row keeps its own state. A stable, unique id works. An array index breaks when rows are deleted or reordered, because the typed text stays at the position and ends up on the wrong item. Page 6.4.3 shows the bug being reproduced.
"What is the children prop?" Whatever is nested between a component's tags. It is how you build wrappers like layouts and cards.
"Why does React use one-way data flow?" Because a value has exactly one owner and travels in one direction, so to find where data came from you only need to look upward. It makes bugs far easier to trace than two-way binding.
One thing to volunteer: say that JSX compiles to function calls and returns plain objects. It shows you see React as ordinary JavaScript, not a mystery, which is what interviewers hope for.
Recall
- React builds the screen from components, each a function that returns a piece of the screen. Write it once, use it many times. The core idea: the screen is a function of the data; you describe what it should look like, and React does the updating.
- A component name starts with a capital letter (lowercase means an HTML tag), returns one root (use a fragment
<>…</>to avoid an extra element), and wraps a multi-line return in parentheses. - JSX looks like HTML but is syntax for function calls; a build tool rewrites it into calls that return plain element objects.
{ }holds any JavaScript expression (not a statement). Attributes are camelCase:className,htmlFor,onClick.styletakes an object, hencestyle={{ … }}. - React escapes values in braces, so normal JSX is safe from script injection;
dangerouslySetInnerHTMLturns that off. - Props are a component's inputs, passed like attributes and received as one object. Type them in TypeScript, destructure them, and give optional ones defaults.
- Data flows down, never up. A child tells its parent something by calling a function the parent passed down. Props are read-only: never change them. Components must be pure.
childrenholds what is nested between a component's tags (typeReactNode); it is how wrappers like panels and layouts work.- Conventions: one component per file in PascalCase, group by feature, keep components small. A bug to avoid:
onClick={fn()}calls the function at once; writeonClick={fn}.
Self-test: Why must a component name start with a capital letter? · What does a build tool turn <h1>Hi</h1> into? · Why are there double braces in style={{ color: 'red' }}? · How does a child component tell its parent that a button was clicked? · What does "pure" mean for a component?
Next: 6.4.2 gives components memory. So far every card is frozen: it shows what it was given. The next page makes the page react to clicks, which is where the name "React" comes from.