Events and forms
Handle an event
Pass a function to a JSX event prop and let React call it when the interaction occurs.
Event handlers run in response to a user interaction.
function SaveButton() {
function handleClick() {
console.log('Saved')
}
return <button onClick={handleClick}>Save</button>
}
Event prop names use camelCase. Pass the function as onClick={handleClick}.
This is wrong:
<button onClick={handleClick()}>Save</button>
It calls the function during rendering and passes its return value to onClick.
Put work caused by the interaction in the handler: update state, submit data, or call a parent callback. Keep rendering pure.
Use the semantic element for the interaction. A button already supports keyboard activation, focus, and disabled behavior. A clickable div makes you rebuild those features.
Name handlers after the event or intent: handleClick, handleSave, or onSave. A clear name makes the data flow easier to follow.
Add a console log inside the component body and another inside the handler. Reload and click once. Notice which log belongs to rendering and which belongs to the event.
Lesson completed