Lesson 2 · Unit 02
Events and inputs
Handlers, controlled inputs, and updating objects and arrays without mutating them.
What you practise
- Handlers, controlled inputs, updating objects and arrays without mutating them
Try a question from this lesson
Pick one
Three ways to attach a handler. One runs save at the wrong moment, and the compiler notices. Which line?
function save() {
console.log('saved');
}
const a = <b onClick={save}>A</b>;
const b = <b onClick={save()}>B</b>;
const c = <b onClick={() => save()}>C</b>;Correct answer
Line 5
Why
save() with parentheses calls the function right now, while rendering, and hands its result (nothing) to onClick. Pass the function itself, or an arrow function that calls it. Lines 4 and 6 run save only on a click.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Handlers
An event handler is a function you pass to a prop such as onClick or onChange. Pass it, do not call it: React calls it when the event happens. Define handlers inside the component, so they can read the props and state of their render. Work with side effects, such as saving, belongs in handlers and never in the rendering code.
Concept
Controlled inputs
value={q} makes the state the single owner of the text. onChange copies each edit into the state, and the re-render shows it. One loop per keystroke. Because the text lives in state, the component can validate it, clear it or use it anywhere else.
key press
→ onChange(e)
→ setQ(e.target.value)
→ React renders again
→ <input value={q}> shows the new text9 more exercises in the app
- 4× multiple choice
- 1× fill the blanks
- 1× match the pairs
- 1× order the lines
- 1× true or false
- 1× type the answer
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.