ProgramGuru

Handling Events

Handling Events

An attendance screen needs to respond when a teacher selects Present. A visible button alone cannot change application data: we must tell React which function should run for that interaction.

An event handler is a function supplied to an element through an event prop such as onClick. React invokes it when the corresponding interaction occurs. Pass a function rather than calling it during rendering.

  1. Explain

    Pass a function to an event prop without calling it during render.

  2. Trace

    Use a callback to request a change from the owning parent.

  3. Apply

    Trace a student-selection click through its handler to the screen.

Events: follow the relationship

  1. Activate a control

    The teacher presses a student-selection button.

  2. Call the handler

    React calls the supplied function in response to that interaction.

  3. Describe the change

    The owning component updates state and returns the selected student.

Read this relationship alongside the complete code. This diagram explains the flow; it does not execute React.

Build the mental model

Separate describing a button from responding to it. Rendering decides the label and handler association. Clicking runs the associated handler. The handler can request a state update, which allows the next render to display the changed information.

Understand the interaction boundary

An event handler can use props and state from the render that created it. It can also receive a parameter through a small wrapper function. In either case, the code runs because an interaction occurred. This is a useful place for an explicit user action such as selecting a student.

A native button already has keyboard activation behavior and a recognizable role. Use type="button" when a button sits inside a form but should not submit it. Otherwise the form’s default submission behavior can run alongside the React handler and unexpectedly navigate the page.

Read the complete React example

The example passes markPresent to onClick. The function is not invoked while constructing the button. In the practice, an arrow function passes a particular student name to the handler so the selected student becomes visible in the status paragraph.

React · JavaScript with JSX

import React, { useState } from 'react';
export default function App() {
  const [status, setStatus] = useState('Not marked');
  function markPresent() {
    setStatus('Present');
  }
  return <main><h1>Attendance</h1><p>{status}</p><button onClick={markPresent}>Mark present</button></main>;
}

Expected screen and behavior

Initial screen: Attendance Not marked Mark present
After selecting Mark present: the screen includes Present.

Connect the source to the screen

React · main example

import React, { useState } from 'react';
export default function App() {
  const [status, setStatus] = useState('Not marked');
  function markPresent() {
    setStatus('Present');
  }
  return <main><h1>Attendance</h1><p>{status}</p><button onClick={markPresent}>Mark present</button></main>;
}

React provides an event object to the handler when you need event information. Events can bubble to ancestors, so a surrounding clickable element may also respond. Use event.stopPropagation when the intended interaction requires stopping that propagation, and preventDefault for a browser default such as form navigation.

Avoid the common mistakes

onClick={markPresent()} calls the function immediately and uses its return value as the handler. This can trigger updates during rendering or leave no useful function to call. Native buttons support keyboard interaction; a clickable div needs additional accessibility work and usually offers no advantage.

Practice before reading the solution

React · starting example

import React, { useState } from 'react';
export default function App() {
  const [status, setStatus] = useState('Not marked');
  function markPresent() {
    setStatus('Present');
  }
  return <main><h1>Attendance</h1><p>{status}</p><button onClick={markPresent}>Mark present</button></main>;
}

Show which of two students was selected using one handler.

Predict the initial visible text and explain which values determine it. Then inspect the worked solution below. Change one relevant input in your local project and check whether the screen follows your prediction. A working screen should be checked for the intended meaning, not merely the absence of an error.

Worked practice solution

The worked example uses a small arrow function for each button to pass its student name. State stores the last selection, while the shared handler describes the action. Both buttons are normal button elements and can be activated with the keyboard.

React · JavaScript with JSX

import React, { useState } from 'react';
export default function App() {
  const [selected, setSelected] = useState('Nobody');
  function chooseStudent(name) {
    setSelected(name);
  }
  return <main><p>Selected: {selected}</p><button onClick={() => chooseStudent('Asha')}>Choose Asha</button><button onClick={() => chooseStudent('Ravi')}>Choose Ravi</button></main>;
}

Expected screen and behavior

Initial screen: Selected: Nobody Choose Asha Choose Ravi
After selecting Choose Asha: the screen includes Selected: Asha.
After selecting Choose Ravi: the screen includes Selected: Ravi.

Check your reasoning

React · main example

import React, { useState } from 'react';
export default function App() {
  const [status, setStatus] = useState('Not marked');
  function markPresent() {
    setStatus('Present');
  }
  return <main><h1>Attendance</h1><p>{status}</p><button onClick={markPresent}>Mark present</button></main>;
}

Choose the explanation that matches React and JavaScript behavior. Review the reasoning for each alternative before moving on.

Which expression passes a click handler without calling it during rendering?
Choose one answer. You can try again.

Answer and explanation

onClick={markPresent}

Correct. It supplies the function for React to invoke when clicked.

Use the idea in the next lesson

An event handler is a function supplied to an element through an event prop such as onClick. React invokes it when the corresponding interaction occurs. Pass a function rather than calling it during rendering.

Continue with useState: Component Memory. Revisit Keeping Components Pure when the relationship between inputs and the resulting screen needs another look.

Read the primary reference: React documentation on Handling Events.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: useState: Component Memory →