Paramclasses Academy - Blog

Tutorials Details

←
Post 9 of 29
→

What is Event Handling in React — Click Events, Input Events, and User Interactions ?

What is Event Handling in React — Click Events, Input Events, and User Interactions ?

October 29, 2026

 

1. Introduction

Modern web applications need to respond to user actions. When a user clicks a button, enters text, submits a form, or selects an option, the application should respond appropriately.

React provides an event-handling system that allows developers to connect user interactions with JavaScript functions.

For example:

  • A button click can increase a counter.

  • Typing in a search box can update search text.

  • Submitting a form can validate the entered information.

  • Clicking a menu button can show or hide a navigation menu.

  • Selecting a product quantity can update the displayed total.

In React, event handlers are JavaScript functions that run in response to specific events. They are commonly used with state to create interactive user interfaces.

In this tutorial, you will learn how to handle common events, access event information, work with forms, and connect event handlers to React state.

2. Learning Objectives

By the end of this tutorial, you will be able to:

  • Understand event handling in React.

  • Handle button click events using onClick.

  • Handle input changes using onChange.

  • Handle form submission using onSubmit.

  • Understand the React event object.

  • Pass arguments to event handlers.

  • Use event handlers with the useState Hook.

  • Prevent the browser's default form-submission behavior.

  • Avoid common event-handling mistakes.

  • Build a practical interactive form.

3. Core Concepts and Explanation

3.1 What Is Event Handling?

An event is an action or occurrence that a program can respond to.

Examples include:

  • click — a user clicks an element.

  • change — an input's value changes.

  • submit — a form is submitted.

  • focus — an input receives focus.

  • blur — an element loses focus.

  • keydown — a keyboard key is pressed.

Event handling means writing code that responds to these events.

In React, event names in JSX use camelCase, and handlers are passed as function references or function expressions.

For example:

<button onClick={handleClick}>Click Me</button>

Here, onClick connects the button's click event to the handleClick function.

3.2 Handling Button Click Events

Let's create a simple React component that responds to a button click.

function App() {
  function handleClick() {
    alert("Button clicked!");
  }

  return (
    <div>
      <h1>Event Handling in React</h1>
      <button onClick={handleClick}>Click Me</button>
    </div>
  );
}

export default App;

How it works:

  1. The handleClick function contains the code to execute.

  2. The button uses onClick={handleClick}.

  3. When the user clicks the button, React calls the function.

  4. An alert displays the message.

Notice that we write onClick={handleClick}, not onClick={handleClick()}.

The first form passes the function to React. The second form invokes the function during rendering, which is generally incorrect for an event handler.

3.3 Using Arrow Functions as Event Handlers

You can also define an event handler directly in JSX using an arrow function.

function App() {
  return (
    <button
      onClick={() => {
        alert("Welcome to Param Classes!");
      }}
    >
      Show Message
    </button>
  );
}

export default App;

This is convenient for short handlers.

For longer logic, a separately named function often makes the component easier to read and maintain.

3.4 Handling Events with State

Event handlers often update state so that the user interface changes after an interaction.

import { useState } from "react";

function App() {
  const [count, setCount] = useState(0);

  function increaseCount() {
    setCount((previousCount) => previousCount + 1);
  }

  return (
    <div>
      <h1>Counter App</h1>
      <h2>Count: {count}</h2>

      <button onClick={increaseCount}>Increase</button>
    </div>
  );
}

export default App;

Each click calls increaseCount, which requests an update to the state. React then renders the new count.

This demonstrates the relationship between event handling and the useState Hook from Tutorial 8.

3.5 Handling Input Events with onChange

The onChange event is commonly used to respond to changes in form fields.

import { useState } from "react";

function App() {
  const [name, setName] = useState("");

  function handleNameChange(event) {
    setName(event.target.value);
  }

  return (
    <div>
      <h1>Name Form</h1>

      <input
        type="text"
        value={name}
        onChange={handleNameChange}
        placeholder="Enter your name"
      />

      <p>Your name: {name}</p>
    </div>
  );
}

export default App;

How it works:

  • value={name} sets the input's displayed value from React state.

  • onChange={handleNameChange} registers the event handler.

  • event.target.value reads the current value of the input.

  • setName(...) updates the state.

Because the input is controlled by React state, the displayed text updates as the user types.

3.6 Understanding the Event Object

React passes event information to an event handler.

For example:

function App() {
  function handleClick(event) {
    console.log("Event type:", event.type);
    console.log("Clicked element:", event.currentTarget);
  }

  return (
    <button onClick={handleClick}>
      Inspect Event
    </button>
  );
}

export default App;

The event object provides useful information about the interaction.

Common properties include:

  • event.type — the event's type, such as "click".

  • event.target — the element where the event originated.

  • event.currentTarget — the element whose handler is currently executing.

  • event.preventDefault() — prevents the browser's default action when the event is cancelable.

For input elements, event.target.value is commonly used to read the entered value.

Important distinction: target and currentTarget can refer to different elements when an event originates from a nested element. Use the property that matches the information you need.

3.7 Passing Arguments to Event Handlers

Sometimes a handler needs a specific value, such as a product ID.

function App() {
  function showProduct(productName) {
    alert(`Selected product: ${productName}`);
  }

  return (
    <div>
      <button onClick={() => showProduct("Laptop")}>
        Select Laptop
      </button>

      <button onClick={() => showProduct("Smart Watch")}>
        Select Smart Watch
      </button>
    </div>
  );
}

export default App;

The arrow function passes the required argument when the user clicks a button.

If you also need the event object, you can pass it explicitly:

<button
  onClick={(event) => showProduct("Laptop", event)}
>
  Select Laptop
</button>

Your function can then accept both parameters.

3.8 Handling Form Submission

React forms commonly use the onSubmit event.

import { useState } from "react";

function App() {
  const [email, setEmail] = useState("");

  function handleSubmit(event) {
    event.preventDefault();
    alert(`Submitted email: ${email}`);
  }

  return (
    <form onSubmit={handleSubmit}>
      <label htmlFor="email">Email:</label>

      <input
        id="email"
        type="email"
        value={email}
        onChange={(event) => setEmail(event.target.value)}
        required
      />

      <button type="submit">Submit</button>
    </form>
  );
}

export default App;

Why use event.preventDefault()?

A standard browser form submission can navigate or reload the page. Calling preventDefault() stops that default action so the React handler can process the form without the normal browser submission.

The required attribute asks the browser to validate that the email field is filled in before allowing submission. More advanced validation may also be needed for real applications.

3.9 Handling Keyboard Events

You can respond to keyboard interactions using events such as onKeyDown.

function App() {
  function handleKeyDown(event) {
    if (event.key === "Enter") {
      alert("Enter key pressed!");
    }
  }

  return (
    <input
      type="text"
      placeholder="Press Enter"
      onKeyDown={handleKeyDown}
    />
  );
}

export default App;

When the user presses Enter while the input is focused, the handler displays an alert.

Keyboard events are useful for shortcuts and custom interaction patterns. However, preserve standard keyboard accessibility when building interactive components.

3.10 Event Handling Best Practices

Follow these principles:

  1. Use camelCase event names such as onClick, onChange, and onSubmit.

  2. Pass function references or arrow functions as event handlers.

  3. Use state when an interaction should update the rendered UI.

  4. Use event.preventDefault() only when you need to prevent the browser's default behavior.

  5. Keep handlers focused on a clear task.

  6. Use meaningful function names, such as handleSubmit and handleNameChange.

  7. Use semantic HTML elements, such as buttons for actions and forms for form submissions.

  8. Ensure interactive elements are usable with a keyboard.

  9. Avoid unnecessary complicated logic directly inside JSX.

4. Practical Code Examples

Example 1: Increase and Decrease Buttons

Create a counter with two buttons.

import { useState } from "react";

function App() {
  const [count, setCount] = useState(0);

  function increase() {
    setCount((value) => value + 1);
  }

  function decrease() {
    setCount((value) => value - 1);
  }

  return (
    <div>
      <h1>Counter</h1>
      <h2>{count}</h2>

      <button onClick={increase}>Increase</button>
      <button onClick={decrease}>Decrease</button>
    </div>
  );
}

export default App;

Expected behavior: The count starts at 0. Increase adds one, while Decrease subtracts one.

Example 2: Show and Hide a Message

import { useState } from "react";

function App() {
  const [visible, setVisible] = useState(false);

  function toggleMessage() {
    setVisible((previousValue) => !previousValue);
  }

  return (
    <div>
      <h1>Message Toggle</h1>

      <button onClick={toggleMessage}>
        {visible ? "Hide Message" : "Show Message"}
      </button>

      {visible && <p>Welcome to Param Classes!</p>}
    </div>
  );
}

export default App;

Expected behavior: The message is initially hidden. Clicking the button displays it, and clicking again hides it.

Example 3: Live Text Preview

import { useState } from "react";

function App() {
  const [message, setMessage] = useState("");

  return (
    <div>
      <h1>Live Text Preview</h1>

      <textarea
        value={message}
        onChange={(event) => setMessage(event.target.value)}
        placeholder="Type your message here"
      />

      <h2>Preview</h2>
      <p>{message || "Your message will appear here."}</p>
    </div>
  );
}

export default App;

Expected behavior: Text typed into the textarea appears immediately in the preview.

This pattern is useful for live previews, message composers, and form interfaces.

Example 4: Complete Contact Form

This example combines input handling, state, form submission, and basic validation.

import { useState } from "react";

function App() {
  const [formData, setFormData] = useState({
    name: "",
    email: "",
  });

  const [submitted, setSubmitted] = useState(false);

  function handleChange(event) {
    const { name, value } = event.target;

    setFormData((previousData) => ({
      ...previousData,
      [name]: value,
    }));

    setSubmitted(false);
  }

  function handleSubmit(event) {
    event.preventDefault();
    setSubmitted(true);
  }

  return (
    <div>
      <h1>Contact Form</h1>

      <form onSubmit={handleSubmit}>
        <label htmlFor="name">Name:</label>
        <input
          id="name"
          name="name"
          type="text"
          value={formData.name}
          onChange={handleChange}
          required
        />

        <br />

        <label htmlFor="email">Email:</label>
        <input
          id="email"
          name="email"
          type="email"
          value={formData.email}
          onChange={handleChange}
          required
        />

        <br />

        <button type="submit">Submit</button>
      </form>

      {submitted && (
        <div>
          <h2>Form Submitted</h2>
          <p>Name: {formData.name}</p>
          <p>Email: {formData.email}</p>
        </div>
      )}
    </div>
  );
}

export default App;

How it works:

  1. formData stores the name and email.

  2. handleChange identifies which input changed.

  3. The computed property [name] updates the appropriate field while preserving the other field.

  4. handleSubmit prevents the default browser submission.

  5. After submission, a confirmation section displays the entered values.

This example demonstrates client-side interaction only. A production contact form should also validate data appropriately and submit it securely to a backend when required.

5. Real-World Applications

Event handling is essential in almost every interactive React application.

E-commerce websites

  • Handle Add to Cart button clicks.

  • Update product quantities.

  • Capture search input and filter selections.

Admin dashboards

  • Open navigation menus.

  • Switch tabs.

  • Respond to table filters and pagination controls.

Registration and login forms

  • Capture input values.

  • Validate required fields.

  • Handle submission and display feedback.

Social applications

  • Like and unlike posts.

  • Submit comments.

  • Open menus and respond to user actions.

Educational applications

  • Start quizzes.

  • Select answers.

  • Track interactions with learning materials.

The key idea is to connect an event to a clearly defined action, and use state when the resulting interaction should change the UI.

6. Common Mistakes and Best Practices

Mistake 1: Calling the Handler During Rendering

Incorrect:

<button onClick={handleClick()}>
  Click Me
</button>

Correct:

<button onClick={handleClick}>
  Click Me
</button>

The incorrect version invokes the function during rendering instead of waiting for the click.

Mistake 2: Using the Wrong Event Name

Incorrect:

<button onclick={handleClick}>Click</button>

Correct:

<button onClick={handleClick}>Click</button>

React event props use camelCase.

Mistake 3: Forgetting preventDefault() in a Custom Form Handler

If you want to handle a form submission entirely in React without the browser's normal form navigation, use:

function handleSubmit(event) {
  event.preventDefault();
  // Process form data.
}

Use this when appropriate for your form behavior.

Mistake 4: Updating State Incorrectly

Incorrect:

setCount(count++);

Correct:

setCount((previousCount) => previousCount + 1);

Avoid incrementing or mutating the state variable directly.

Mistake 5: Forgetting the Input's value or onChange

For a controlled input, provide both a state-backed value and an onChange handler that updates the state. Otherwise, the field may become difficult or impossible to edit as intended.

Best Practices

  • Keep event handlers readable and focused.

  • Use semantic buttons and labels.

  • Prefer functional state updates when the next value depends on the previous one.

  • Use controlled inputs when React state needs to track form values.

  • Prevent default browser behavior only when required.

  • Use meaningful IDs and htmlFor attributes for form labels.

  • Do not rely solely on client-side validation for sensitive or important data.

  • Keep keyboard accessibility in mind when implementing interactions.

7. Practice Exercises

Complete these exercises to reinforce what you learned.

Exercise 1: Click Event

Create a button that displays an alert when clicked.

Exercise 2: Counter

Build a counter with Increase, Decrease, and Reset buttons.

Exercise 3: Input Handling

Create an input field that displays the entered text below it.

Exercise 4: Show and Hide

Build a button that toggles the visibility of a paragraph.

Exercise 5: Keyboard Event

Display a message when the user presses Enter in an input field.

Exercise 6: Contact Form

Create a form with name and email fields. Prevent the default submission and display the entered values after submission.

Exercise 7: Product Selection

Display three product buttons. When a user clicks one, display the selected product name.

Self-check Questions

  1. What is event handling in React?

  2. How is onClick used?

  3. Why should you pass a function reference instead of calling the handler during rendering?

  4. How do you read an input's current value?

  5. What is the event object?

  6. What does event.preventDefault() do?

  7. How can you pass arguments to an event handler?

  8. How do event handlers work with useState?

  9. What is a controlled input?

  10. Why should form validation also be considered on the server for production applications?

8. Key Takeaways and Conclusion

In this tutorial, you learned that:

  • Event handling allows React applications to respond to user interactions.

  • Common event handlers include onClick, onChange, onSubmit, and onKeyDown.

  • React event props use camelCase.

  • Event handlers are JavaScript functions.

  • The event object provides information about an interaction.

  • State updates let interactions change the rendered UI.

  • event.preventDefault() can stop default browser behavior.

  • Controlled inputs keep their displayed values synchronized with React state.

  • Semantic HTML and clear event handlers make applications easier to use and maintain.

Final takeaway: Event handling connects the user's actions to your application's behavior. Combined with props and state, it is a fundamental building block of interactive React applications.

←
Post 9 of 29
→