React events use camelCase props such as onClick, onChange and onSubmit. Pass a function; do not call it while rendering.
Event handlers
function TaskButton() { function handleClick() { console.log("Task selected"); } return ( <button className="button button--primary" onClick={handleClick} > Select task </button> ); }
onClick={handleClick} gives React the function. Writing onClick={handleClick()} calls it immediately. Use an inline arrow function when you need to pass an argument: onClick={() => onDelete(id)}.
Passing handlers
A parent can pass a handler as a prop so a child reports an interaction without owning the data. Name the prop for the meaning of the event, such as onComplete, rather than the physical interaction; the component can later support a keyboard as well as a click.
What happens after a click
- Rendering passes a function reference to
onClick. - The browser reports a click and React calls that function with an event object.
- The handler calculates a value or asks an owner to update state.
- If state changes, React renders the affected components again.
Events still propagate through the DOM. Use event.stopPropagation() only when necessary, and avoid nested interactive elements.
Challenge: report which task was clicked
Give TaskItem an id and onDelete prop. Add a Delete button that calls the parent function with that id. Nothing should happen during rendering.
<button
className="task__delete button button--danger"
onClick={() => onDelete(id)}
>
Delete
</button>
The arrow creates a function for React to call later.
