JavaScript 10 · JavaScript for React
JS patterns you meet everywhere in React
Lists with map, conditions in JSX, functions in onClick, state updates and closures in components.
Loading lesson…
JavaScript 10 · JavaScript for React
Lists with map, conditions in JSX, functions in onClick, state updates and closures in components.
Loading lesson…
At first sight the line tasks.map((t) => (t.id === id ? { ...t, done: !t.done } : t)) looks like a React spell. Yet there's no React in it at all: an arrow function, a ternary, an object spread and an array method. Everything from the previous lessons.
This lesson is the bridge between JavaScript and React. We'll go through exactly where the individual pieces of JS show up in components – and in the next lessons you'll recognise them at a glance. You don't need to understand React in depth yet; lessons React basics 01 and 03 explain JSX and useState in detail. Here it's about the JavaScript around them.
First, two words you'll see in every example. A page is made of HTML tags: <h1> is a heading, <p> a paragraph, <button> a button, <ul> and <li> a list and its items. A tag opens with <p>, closes with </p> and the content goes in between; it can also have attributes, like <input type="checkbox" />.
JSX is a way to write these tags right in JavaScript. It looks like HTML, but it is JavaScript: <h1>Hello</h1> is turned into a function call that makes a heading when the project is built. That's why you can return it from a function, store it in a variable or put it in an array. A component is a function that returns such a piece of the page.
// A component = an ordinary function (with a capital letter) that returns JSXfunction Greeting(props) {return <h1>Hello, {props.name}!</h1>}// Destructuring the parameter (lesson JavaScript 03) + a default value (lesson JavaScript 02)function Greeting({ name, greeting = 'Hello' }) {return <h1>{greeting}, {name}!</h1>}// Usage: the attributes are collected into ONE props object<Greeting name="Anna" /> // props = { name: 'Anna' }<Greeting name="Peter" greeting="Hi" /> // props = { name: 'Peter', greeting: 'Hi' }
// Take out what you need and pass the rest onfunction Button({ variant = 'primary', ...rest }) {return <button className={`btn btn-${variant}`} {...rest} />// className = the HTML attribute class (a CSS class); {...rest} = spread all properties of rest here as attributes}// save = a function that saves something (made up for the example)<Button variant="ghost" onClick={save} disabled>Save</Button>// rest = { onClick: save, disabled: true, children: 'Save' } → <button> gets all of it// (children = the content between the opening and closing tag; disabled without a value means true)
Curly braces in JSX are a window through which you insert an expression – anything that has a value. Statements (if, for, const) don't belong inside; you write them above the return.
// {/* … */} is a comment inside JSX (a plain // doesn't work there)function Price({ amount, discount }) {// ✅ Statements and intermediate calculations above returnconst final = amount - discountconst isFree = final <= 0return (<p>${final} {/* a variable */}${amount * 1.2} with tax {/* a calculation */}{formatPrice(final)} {/* a function call (formatPrice = a made-up function for a nice price) */}{isFree ? 'Free!' : `Price: $${final}`} {/* a ternary, a template */}{/* {if (isFree) …} ❌ if isn't an expression */}</p>)}
// A template string for combined CSS classes (done, urgent = true/false)<li className={`task ${done ? 'task-done' : ''} ${urgent ? 'task-urgent' : ''}`}>// An object with styles – the outer { } is the window into JS, the inner { } is an object<div style={{ color: 'red', fontSize: 14 }}>// CSS properties are written in camelCase here (fontSize instead of font-size) and a number means pixels
There's no for in JSX. A list is rendered by turning an array of data into an array of elements with map – React can render an array of elements:
const fruits = ['apple', 'pear', 'plum']<ul>{fruits.map((fruit) => <li key={fruit}>{fruit}</li>)}</ul>// map returns [<li>apple</li>, <li>pear</li>, <li>plum</li>]// key = a unique label of every item, by which React tells which one is which
function TodoList({ todos, query }) {// filter above return – derived dataconst visible = todos.filter((t) => t.title.toLowerCase().includes(query.toLowerCase()))if (visible.length === 0) return <p>Nothing found.</p> // early return for the empty statereturn (<ul>{visible.map((todo) => (<li key={todo.id}> {/* key: a stable id from the data */}{todo.title}</li>))}</ul>)}
The table shows how to choose in JSX what gets drawn. <Profile />, <Login /> and <ErrorBox /> are made-up components – just like <Greeting /> above – and isLoggedIn, hasError, user and status are variables from the surrounding code.
| I want… | Syntax |
|---|---|
| two versions | {isLoggedIn ? <Profile /> : <Login />} |
| something, or nothing | {hasError && <ErrorBox />} |
| to render nothing at all | if (!user) return null |
| loading / error / data | an early return for each state |
| a version based on a value | {ICONS[status]} |
// The props come from the parent, e.g.:// <UserPanel isLoading={false} error={null} user={{// name: 'Jane', isAdmin: true, messages: ['Hi', 'Tomorrow?'],// bio: null, // Jane hasn't filled in a description of herself// address: null, // nor an address// }} />// After → is what gets rendered for this data (?? and ?. are from lesson JavaScript 06).function UserPanel({ user, isLoading, error }) {// early return – deal with each state and stop (lesson JavaScript 06)if (isLoading) return <p>Loading…</p> // the data is still loadingif (error) return <p className="error">{error}</p> // error = the error text, or null when there is noneif (!user) return null // null = render nothingreturn (<div><h2>{user.name}</h2> {/* → Jane */}{user.isAdmin && <span>Admin</span>} {/* → Admin (isAdmin is true; with false nothing would be here) */}{user.messages.length > 0 && ( {/* ✅ a comparison, not a bare number */}<span>Messages: {user.messages.length}</span>)} {/* → Messages: 2 */}<p>{user.bio ?? 'No description'}</p> {/* → No description: bio is null, so ?? takes the text on the right */}{/* (if bio were 'Learning React', that would be shown) */}<p>{user.address?.city}</p> {/* → an empty paragraph: address is null, so ?. returns undefined */}{/* instead of an error, and React renders nothing for undefined */}</div>)}
What you see: A small catalogue. In the code (the Code button) you'll find filter, map with key, a ternary, &&, a template string for a CSS class, a dictionary of icons and reduce for a sum – all commented.
Try it:
The takeaway: A component is largely plain JavaScript: the data is prepared above the return (filter, reduce) and in JSX it's only put together (map, ternary, &&).
Loading the interactive part…
You pass onClick a function that React calls on a click (lesson JavaScript 02) – not the result of calling it:
function handleClick() {alert('Clicked!')}// The todo the × button belongs to (in an app it would come from todos.map((todo) => …), section 3)const todo = { id: 2, title: 'Tidy up', done: false }function remove(id) {// deletes the todo with this id from the list – how exactly, section 6 shows;// here it's only about WHEN the function gets called}<button onClick={handleClick}>OK</button> // ✅ you pass the function<button onClick={handleClick()}>OK</button> // ❌ you call it RIGHT AWAY while rendering<button onClick={() => remove(todo.id)}>×</button> // ✅ you need an argument → wrap it in an arrow<button onClick={remove(todo.id)}>×</button> // ❌ it gets deleted while rendering!
The difference is in what gets stored in onClick. () => remove(todo.id) is a new function that doesn't do anything yet – React keeps it and calls it only on a click, and only then does it call remove(2). But remove(todo.id) without the arrow is a call: JavaScript runs it right away, while React is rendering the button, so the todo disappears without anyone clicking. What ends up in onClick is whatever remove returned (here undefined), and the click then does nothing.
// React passes the handler an event object// onChange = the change handler: it's called on every typed character (on a checkbox when it's ticked)// setName, setOn, setAge = functions that store the new value in state (section 6)// e.target = the element the event happened on (here the field)<input onChange={(e) => setName(e.target.value)} /> // the text from the input (always a string!)<input type="checkbox" onChange={(e) => setOn(e.target.checked)} /><input type="number" onChange={(e) => setAge(Number(e.target.value))} /> // conversion (lesson JavaScript 01)function handleSubmit(e) {e.preventDefault() // otherwise the form would reload the page// …}<form onSubmit={handleSubmit}>
// The parent has its own functions (convention: handle…) and passes them to the child as props (convention: on…);// the child calls them when the user clicks – it can't delete todos itself, it just lets the parent knowfunction TodoItem({ todo, onToggle, onDelete }) {return (<li><input type="checkbox" checked={todo.done} onChange={() => onToggle(todo.id)} />{todo.title}<button onClick={() => onDelete(todo.id)}>×</button></li>)}<TodoItem todo={todo} onToggle={handleToggle} onDelete={handleDelete} />// handleToggle and handleDelete are the parent's functions that toggle or delete a todo by id
const [count, setCount] = useState(0)// useState returns an array [value, function to change it] – array destructuring (lesson JavaScript 03)// you choose the names; the convention is x / setX
State is never changed directly. You always pass a new value – for objects and arrays a new object or a new array (the whole of lesson JavaScript 09):
// newTodo = a new todo, e.g. { id: 3, title: 'Take out the bin', done: false }// id = the id of the todo you're deleting or changing, e.g. 2 – in an app you get it as a parameter// of the function a click on that todo calls (the same lines with their results are in lesson JavaScript 09)setCount(count + 1) // a numbersetName(e.target.value) // textsetUser({ ...user, name: 'Eve' }) // an object – spreadsetTodos([...todos, newTodo]) // addsetTodos(todos.filter((t) => t.id !== id)) // removesetTodos(todos.map((t) => (t.id === id ? { ...t, done: !t.done } : t))) // change onetodos.push(newTodo) // ❌ a mutation – React doesn't notice the changesetTodos(todos) // ❌ still the same array
setCount(count + 1) // a new value calculated from count in THIS rendersetCount((c) => c + 1) // a function: "take the current value and add 1"setTodos((prev) => [...prev, newTodo]) // the same for an array
Why are there two forms? Because of closures – see the next section.
A component is a function, and React calls it again on every render. Every call has its own variables – its own count, its own handleClick. Functions created in one render carry the values from that render in their backpack (closure, lesson JavaScript 02). It's like a photo: it captures the state at the moment it was taken.
function Counter() {const [count, setCount] = useState(0)function addLater() {setTimeout(() => {setCount(count + 1) // count is the value from the render in which you clicked}, 2000)}// Click 3 times quickly: all three timeouts see count = 0 → the result is 1, not 3function addLaterFixed() {setTimeout(() => {setCount((c) => c + 1) // React passes the current value → the result is 3}, 2000)}}
What you see: A counter and two buttons that add one only after 2 seconds – each in a different way.
Try it:
count.The takeaway: When the new value depends on the previous one and changes can pile up (timers, several changes in a row), use the updater setX((prev) => …).
Loading the interactive part…
An event handler can be an async function – typically submitting a form (lesson JavaScript 07):
function SignupForm() {const [isSending, setIsSending] = useState(false)const [error, setError] = useState(null)async function handleSubmit(e) {e.preventDefault()setIsSending(true)setError(null)try {await registerUser({ name, email }) // wait for the server (registerUser = a function that sends the data to the server;// name and email are the form fields' state, left out here)alert('Done!')} catch (err) {setError(err.message) // show the error} finally {setIsSending(false) // loading is over either way}}return (<form onSubmit={handleSubmit}>…<button disabled={isSending}>{isSending ? 'Sending…' : 'Sign up'}</button>{error && <p className="error">{error}</p>}</form>)}
Render an array of names as a list and show how many there are.
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…
A list with ready-made state and looks, in which the JavaScript is missing: showing the real items, picking them by the filter and counting how many are left to buy. The steps go from the top of the code to the bottom and each one has its own ✅.
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…
A follow-up: the same list, which already shows and filters the items. Now you add adding, ticking off and deleting an item – every one of them a pattern from this part of the course. What exactly each place should do is in the comments in the code.
Medium and hard challenges unlock once you sign in. Like the whole course, they are free – just an e-mail, no password and no payment.
key. Filter above the return, handle the empty state with a ternary or an early return.onClick={fn} passes the function, onClick={fn()} calls it right away. With an argument () => fn(x).setX((prev) => …).