DEV Community

Sravanthi
Sravanthi

Posted on

Event Handling in React

Introduction

After learning about state, I started wondering how React responds when a user interacts with the application.

For example:

  • What happens when a button is clicked?
  • How do we update state when a user types into an input field?
  • How do we respond when a form is submitted?

The answer is event handling.

Event handling allows React components to respond to user actions such as clicks, keyboard input, form submissions, and mouse events.

In this article, I'll explain how event handling works in React, how it differs from HTML events, and how it interacts with state.

What is an Event?

An event is an action performed by the user or the browser that React can respond to.

Some common events include:

  • Clicking a button (click event)
  • Typing in a text box (change event)
  • Submitting a form (submit event)
  • Moving the mouse (mouseOver event)
  • Pressing a key (keyDown event)

React uses JavaScript functions called event handlers to respond to these events.

What is Event Handling?

Event handling is the process of responding to user or browser events by executing JavaScript functions.

Example:

  • When a user clicks a button, run a function.
  • When a user types, update state.
  • When a form is submitted, prevent the page from refreshing and process the data.

onClick

onClick is triggered when the user clicks an element such as a button.

React onClick event example

React onClick event example output

When the user clicks the button, React executes the function.

If no arguments are needed, you can pass the function directly. Otherwise, use an arrow function.

Why Do We Use an Arrow Function?

We use an arrow function when we need to pass arguments to an event handler. The arrow function delays calling the function until the button is clicked.

What Happens If We Don't Use an Arrow Function?

The function executes immediately when the component renders instead of waiting for the click event.

This means:

  • The alert appears as soon as the page loads.
  • Clicking the button does nothing because the function has already been called. This is not the desired behavior.

onChange

onChange is triggered whenever the value of an input field changes. It is commonly used with textboxes, dropdowns, and checkboxes.

It is commonly used together with state to keep the UI synchronized with the user's input.

React onChange example
React onChange example output

onSubmit

onSubmit is triggered when a form is submitted. It is commonly used to process form data.

React onSubmit example
React onSubmit example output

What is preventDefault()?

The preventDefault() method is commonly used with onSubmit to stop the browser from refreshing the page, allowing React to process the form data without reloading the application.

For a form, the default behavior is:

  • Submit the form.
  • Refresh the page.

React applications usually don't want the page to refresh, so we use:

e.preventDefault();
Enter fullscreen mode Exit fullscreen mode

This keeps the page open so React can handle the form submission.

Without preventDefault()

User clicks Submit
       ↓
Browser refreshes the page
       ↓
Data is lost
Enter fullscreen mode Exit fullscreen mode

With preventDefault()

User clicks Submit
       ↓
React handles the form
       ↓
Page does NOT refresh
       ↓
Data is processed
Enter fullscreen mode Exit fullscreen mode

Common Events

Event Description
onClick Button click
onChange Input value changes
onSubmit Form submitted
onMouseOver Mouse moves over an element
onKeyDown Keyboard key pressed
onFocus Element receives focus
onBlur Element loses focus

Event Object

An event object is an object that React automatically passes to an event handler whenever an event occurs (such as a click, typing in a textbox, or submitting a form).

It contains information about the event and the element that triggered it, such as:

  • Which element triggered the event.
  • The current value of an input.
  • The type of event.
  • Methods like preventDefault().

The event object is usually named e or event.

Commonly Used Properties

Property Description
e.target The element that triggered the event.
e.target.value Gets the current value of an input field.
e.type Returns the event type (e.g., click, change, submit).
e.preventDefault() Prevents the browser's default behavior, such as refreshing the page on form submission.

Event Handling in HTML vs React

HTML React
Uses lowercase event names (onclick) Uses camelCase (onClick)
Uses strings Uses JavaScript functions
onclick="save()" onClick={save}

Rules of Event Handling

  • Use camelCase event names.
  • Pass a function, not the result of a function.
  • Use arrow functions when passing arguments.
  • Update state using the setter function.
  • Use preventDefault() for forms when needed.

Conclusion

Event handling is what makes React applications interactive. By connecting user actions to JavaScript functions, React can respond to clicks, keyboard input, and form submissions.

Combined with state, event handling allows React components to respond to user actions and automatically update the UI.

As I continue learning React, I'm starting to see how state and event handling work together to build dynamic and interactive user interfaces.

Key Takeaways

  • Event handling allows React to respond to user actions such as clicking, typing, and submitting forms.
  • React event names use camelCase, such as onClick, onChange, and onSubmit.
  • Event handlers are passed as functions, not function calls.
  • Use an arrow function when you need to pass arguments to an event handler.
  • React automatically passes an event object (e) to the event handler.
  • The event object provides information about the event, such as the element that triggered it and its value.
  • Use e.preventDefault() to stop the browser's default behavior, such as refreshing the page after a form submission.
  • State is commonly updated inside event handlers using setter functions like setState or setCount.
  • Event handling makes React applications interactive and responsive to user input.

What's Next?

Now that I know how to respond to user interactions, the next step is learning how to render lists of data in React using the map() method.

In the next article, I'll explore how to display collections of data efficiently and assign keys to list items.

Thanks for reading, and happy coding!

Top comments (0)