Pass event handlers without invoking them
Connect a button to an action
An event is a notification that something happened, such as a button being activated. A handler is a function that responds to it. In JSX, pass the function itself to the event prop. These independent App.jsx examples use the approved Chapter 3 project with React DOM and the automatic JSX transform. All screen and console results are predictions until browser testing is available.
export default function App() { function handleClick() { console.log('Trail map requested'); } return <main><h1>Trail information</h1> <button type="button" onClick={handleClick}>Request map</button> </main>;}Initially the page displays a heading and a button. Activating the button writes Trail map requested to the developer console; the page text does not change. A native button supports ordinary pointer and keyboard activation. The onClick prop is camelCase; handleClick is a naming convention, not a reserved name.
Pass information through a callback
import { useState } from 'react';
function TrailButton({ name, onSelect }) { return <button type="button" onClick={() => onSelect(name)}>{name}</button>;}
export default function App() { const [selected, setSelected] = useState('None'); function handleSelect(name) { setSelected(name); } return <main><h1>Choose a trail</h1> <TrailButton name="Oak loop" onSelect={handleSelect} /> <TrailButton name="Lake path" onSelect={handleSelect} /> <p role="status">Selected: {selected}</p> </main>;}Initially Selected: None is visible. Choosing Lake path changes it to Selected: Lake path. The arrow function delays the call and supplies the name. onSelect is a custom prop; TrailButton explicitly connects it to a built-in button event. The state pair is a preview from Chapter 8: the setter requests a new render. A handler reads the values from the render that supplied it; calling the setter does not rewrite those variables. Chapter 10 covers state in depth.
Do not call the action during render
export default function App() { function handleClick() { console.log('Map requested'); } return <button type="button" onClick={handleClick()}>Request map</button>;}The function logs during rendering and returns undefined, so the button has no useful click handler. Render may happen more than once, particularly in development. Replace handleClick() with handleClick. If you need arguments, use an arrow function as in the previous example. A function call that intentionally returns a handler is a different pattern; do not confuse it with directly invoking an action.
Practice
Create two reusable route buttons that pass a route name to the parent. Show the selected name in a status paragraph. Predict the initial view and the result of activating each button; use keyboard activation as well as a pointer.