React Events Tutorial: onClick, Forms and Runnable Examples

Build one PracticeTracker component, follow every click, change and submit, then learn exactly when to use preventDefault and stopPropagation.

KnowledgeGate Team

Exam prep & CS education

Updated 3 Dec 20265 min read
React Events Tutorial: onClick, Forms and Runnable Examples

JSX looks like HTML, but React does not expect a string in onClick, and your handler must not run while the component is rendering. PracticeTracker uses a button click, a controlled input and a form submit, and a child-button click bubbles through its handlers. You need basic JavaScript functions and state. If either feels unfamiliar, begin with KnowledgeGate's free courses for GATE, placements and CS.

React events from zero: event, handler and state update

An event is a user or browser action, such as a click, an input change or a form submission. An event handler is the function React calls in response. The causal chain is simple: interaction, handler call, optional state update, then a rerendered UI.

React event props use camelCase, and their values are functions. Write onClick={handleAdd}, not onclick="handleAdd()". In that correct expression, onClick is the event prop, handleAdd is the handler, and a setter such as setScore requests the state update. For the underlying elements, forms and browser terms, revise Web Technologies for Teaching Exams: HTML and HTTP.

Pass a handler, do not call it during render

Here is the basic click pattern:

jsx
function handleAdd() {
  setScore(current => current + 1);
}

<button onClick={handleAdd}>Add 1</button>

React receives the handleAdd function and calls it after the click. By contrast, <button onClick={handleAdd()}>Add 1</button> calls handleAdd during rendering and passes its return value to onClick. That is incorrect, not a style choice.

When a handler needs an argument, wrap the call in a function:

jsx
function addPoints(amount) {
  setScore(current => current + amount);
}

<button type="button" onClick={() => addPoints(5)}>Add 5</button>

The arrow creates a function that React can call later. A short inline handler is fine when it remains readable. A separate named handler is useful when the logic grows or is reused.

Worked example: click, change and submit in one component

Copy this complete component into a React project:

jsx
import { useState } from "react";

export default function PracticeTracker() {
  const [score, setScore] = useState(2);
  const [topic, setTopic] = useState("Events");
  const [saved, setSaved] = useState("");

  function addPoints(amount) {
    setScore(current => current + amount);
  }

  function handleSubmit(event) {
    event.preventDefault();
    setSaved(`${topic}: ${score}`);
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Topic
        <input
          value={topic}
          onChange={event => setTopic(event.target.value)}
        />
      </label>
      <p>Score: {score}</p>
      <button type="button" onClick={() => addPoints(5)}>Add 5</button>
      <button type="submit">Save</button>
      {saved && <p role="status">Saved: {saved}</p>}
    </form>
  );
}

Initially, the input shows Events, the score is 2, and there is no status line. Replace the input with React Events. Click Add 5 twice: the first click gives 2 + 5 = 7, and the second gives 7 + 5 = 12. Equivalently, 2 + 5 + 5 = 12. Now click Save. preventDefault() stops the form's normal navigation, and the status becomes Saved: React Events: 12.

The functional update current => current + amount matters because each update receives the latest queued score. Two increments therefore compose correctly. Do not expect reading score immediately after setScore in the same running handler to reveal the new value.

A left-to-right React event and state trace shows topic changing from Events to React Events, score increasing from 2 to 12, and saved text becoming React Events: 12.

Read the event object: target, currentTarget and default action

React supplies the event object as the handler's first argument. In PracticeTracker, event.target.value is the input's current text. In handleSubmit, event.preventDefault() prevents the browser's default form submission behaviour.

Now consider <button onClick={handleSave}><span>Save</span></button>. If the user clicks the letters inside the span, event.target.tagName is SPAN, because the span originated the event. event.currentTarget.tagName is BUTTON, because the handler belongs to the button.

Use target when the originating element matters. Use currentTarget when you need the element whose handler is running. Also keep the operations separate: preventDefault() blocks a browser default action. It does not stop an event from bubbling to an ancestor.

Bubbling and stopPropagation with an exact log

This runnable fragment starts with an empty log. The button handler appends "button", and the section handler appends "panel":

jsx
import { useState } from "react";

export default function EventLog() {
  const [log, setLog] = useState([]);

  return (
    <section onClick={() => setLog(current => [...current, "panel"])}>
      <button
        type="button"
        onClick={() => setLog(current => [...current, "button"])}
      >
        Add to log
      </button>
      <p>{log.join(" > ")}</p>
    </section>
  );
}

One button click produces button > panel: the inner handler runs, then the event bubbles to the section. To stop that path, accept the event in the button handler, append "button", then call event.stopPropagation(). After resetting the log to [], one click now produces only button. This stops this event from continuing to the ancestor handler. It does not cancel the button's default action or replace any state update.

jsx
onClick={event => {
  setLog(current => [...current, "button"]);
  event.stopPropagation();
}}

Method

Exact job

preventDefault()

Blocks a browser default action, such as form submission

stopPropagation()

Stops the event from continuing to ancestor handlers

Do not add either method automatically to every handler. Use the one that matches the behaviour you actually need.

A two-lane bubbling trace shows button clicks logging button then panel without propagation control, or only button with stopPropagation, while preventDefault is unused.

Common React event mistakes and their exact fixes

Match each symptom to its cause and fix:

  • onClick={addPoints(5)} runs during render. Pass onClick={() => addPoints(5)}.

  • onclick is not the React prop spelling. Use onClick.

  • Changing score directly bypasses React's setter. Use setScore.

  • A non-submit button inside a form submits unexpectedly. Give it type="button".

  • Expecting score to change inside the same running handler gives stale reasoning. Derive the next value yourself or use a functional update.

  • value={topic} without onChange makes the controlled field effectively read-only. Keep it with onChange={event => setTopic(event.target.value)}.

If functions, closures or arrow syntax are the difficult part, work through the Complete JavaScript Course before adding more event logic.

Original practice and interview checks

Try these extensions without changing the component's event model:

  1. Change the increment from 5 to 3. From score 2, three clicks produce 2 + 3 + 3 + 3 = 11.

  2. Add a Reset button with type="button". It should set score to 0 and saved to "" without submitting the form.

  3. On submit, if topic.trim() is empty, show Enter a topic without overwriting the last valid saved value.

Check your explanations too. onClick={addPoints(5)} invokes the function during render. Clicking the nested span gives target SPAN and currentTarget BUTTON. With stopPropagation(), the bubbling log contains only button. These checks test React event props and state updates. For capture, delegation, closest(), and dynamic DOM rows, use JavaScript Event Delegation: Bubbling, target and currentTarget; that tutorial owns browser listener mechanics, while this one owns React component handlers, controlled state and form submission.

Short version and next step

Pass a function to an event prop. Take the event object only when needed. Update state through its setter. Choose preventDefault() or stopPropagation() only for the behaviour each controls. In the worked sequence, the topic is React Events, the score is 12, and the saved text is React Events: 12.

For a structured learning path, continue with the React and Redux Course. Rebuild PracticeTracker without copying it, then add all three exercises.