ReactJS Events

User interaction is the foundation of any modern web application. Clicking buttons, typing text, submitting forms, or moving the mouse are all actions that users perform constantly. In React, these interactions are handled using React Events.

Understanding React events is critical because they connect user actions, state changes, and UI updates. Whether you are building a simple form or a complex dashboard, events play a central role.


What Are Events in React?

Events in React represent user actions performed on UI elements, such as:

  • Clicking a button
  • Typing into an input
  • Submitting a form
  • Hovering over elements
  • Pressing keyboard keys

React allows components to respond to these actions by attaching event handlers to elements.


How React Events Work?

React uses a system called Synthetic Events. Instead of working directly with browser events, React creates a synthetic event that wraps the original event.

This approach:
  • Ensures consistent behavior across browsers
  • Provides a unified event API
  • Improves performance through internal optimizations

Event Naming Convention in React

React uses camelCase for event names.

HTML Event React Event Description
onclick onClick Triggers when user clicks on an element (button, div, link).
onchange onChange Triggers when user changes the value of an input, select, or textarea.
onsubmit onSubmit Executes when a form is submitted.
onmouseover onMouseOver Triggered when the mouse pointer moves over an element.
onkeydown onKeyDown Fires when a key on the keyboard is pressed down.

Lets understand how each one of these works in react with examples.


1. onClick – Handling Click Events

A click event is triggered when a user interacts with an element—such as pressing a button or selecting an image—and the browser executes a corresponding action.

In React, handling this interaction is straightforward by attaching a function to the onClick attribute of the element.

Functional Component Example

function OnClickExample() { 
  function handleClick() {
    alert("Button clicked");
  }

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

Class Component Example

class OnClickExample extends React.Component { 
  handleClick() {
    alert("Button clicked");
  }

  render() {
    return (
      <button onClick={() => this.handleClick()}>Click Me</button>
    );
  }
}

Common use cases
  • Submitting actions
  • Opening modals
  • Incrementing counters

2. onChange – Tracking Input Changes

The onChange event is fired whenever the value of an input element—such as a text box, textarea, or dropdown—gets updated by the user. This could happen while typing, selecting an option, or modifying existing input.

In React, onChange is commonly used to capture user input in real time and keep the component state in sync with form fields. It plays a key role in building controlled components, where the UI always reflects the latest data entered by the user.

Functional Component Example

function OnChangeExample() { 
  const [value, setValue] = React.useState("");

  function handleChange(event) {
    setValue(event.target.value);
  }

  return (
    <>
      <input type="text" onChange={handleChange} />
      <p>{value}</p>
    </>
  );
}

Class Component Example

class OnChangeExample extends React.Component {
  state = { value: "" };

  handleChange(event) {
    this.setState({ value: event.target.value });
  }

  render() {
    return (
      <>
        <input type="text" onChange={(e) => this.handleChange(e)} />
        <p>{this.state.value}</p>
      </>
    );
  }
}

Common use cases
  • Controlled forms
  • Search boxes
  • Live input validation

3. onSubmit – Handling Form Submission

The onSubmit event is triggered when a user submits a form, typically by clicking a submit button or pressing the Enter key inside an input field. This event signals that the user has finished entering data and is ready to send it for processing.

In React, onSubmit is used to manage how form data is handled before it is sent to a server or used within the application.

Functional Component Example

function OnSubmitFormExample() { 
  function handleSubmit(event) {
    event.preventDefault();
    console.log("Form submitted");
  }

  return (
    <form onSubmit={handleSubmit}>
      <button type="submit">Submit</button>
    </form>
  );
}

Class Component Example

class OnSubmitFormExample extends React.Component { 
  handleSubmit(event) {
    event.preventDefault();
    console.log("Form submitted");
  }

  render() {
    return (
      <form onSubmit={(e) => this.handleSubmit(e)}>
        <button type="submit">Submit</button>
      </form>
    );
  }
}

Common Use Cases:
  • Login and registration forms
  • Contact forms
  • Preventing page reload during form submission

4. onMouseOver – Mouse Enter Event

The onMouseOver event occurs when the user moves the mouse pointer onto an element or one of its child elements. It helps detect when an element gains focus due to a mouse interaction.

In React, onMouseOver is commonly used to enhance user experience by adding interactive behaviors such as highlighting buttons, showing tooltips, displaying preview information, or triggering animations. Since it responds immediately when the cursor enters the element area, it is useful for providing visual feedback and making interfaces feel more responsive and engaging.

Functional Component Example

function OnMouseOverExample() { 
  function handleMouseOver() {
    console.log("Mouse entered");
  }

  return (
    <div onMouseOver={handleMouseOver}>Hover over me</div>
  );
}

Class Component Example

class OnMouseOverExample extends React.Component { 
  handleMouseOver() {
    console.log("Mouse entered");
  }

  render() {
    return (
      <div onMouseOver={() => this.handleMouseOver()}>Hover over me</div>
    );
  }
}

Common Use Cases:
  • Showing tooltips or hints
  • Highlighting UI elements
  • Revealing additional information on hover

5. onMouseOut – Mouse Leave Event

The onMouseOut event is fired when the mouse pointer moves away from an element or exits its boundary, including its child elements. It indicates that the user is no longer interacting with that part of the interface. onMouseOut is often paired with onMouseOver to reverse or reset visual changes.

Functional Component Example

function MouseOutExample() {
  function handleMouseOut() {
    console.log("Mouse left");
  }

  return (
    <div onMouseOut={handleMouseOut}>Move mouse away</div>
  );
}

Class Component Example

class MouseOutExample extends React.Component {
  handleMouseOut() {
    console.log("Mouse left");
  }

  render() {
    return (
      <div onMouseOut={() => this.handleMouseOut()}>Move mouse away</div>
    );
  }
}

Common Use Cases:
  • Hiding tooltips
  • Resetting hover styles
  • Closing hover-based menus
  • Removing highlight effects

6. onKeyDown – Detecting Keyboard Input

The onKeyDown event is triggered the moment a user presses a key on the keyboard, before the key is released. It allows applications to react instantly to keyboard actions.

onKeyDown tracks which key is pressed and allows you to respond based on that key.

Functional Component Example

import React from "react";

function KeyDownExample() {
  const handleKeyDown = (event) => {
    if (event.key === "Enter") {
      alert("Enter key pressed!");
    } else if (event.key === "Escape") {
      alert("Escape key pressed!");
    } else {
      console.log(`Key pressed: ${event.key}`);
    }
  };

  return (
    <div>
      <h3>Keyboard Event Example</h3>
      <input
        type="text"
        placeholder="Press Enter or Escape"
        onKeyDown={handleKeyDown}
      />
    </div>
  );
}

export default KeyDownExample;

Class Component Example

import React, { Component } from "react";

class KeyDownExample extends Component {
  handleKeyDown(event) {
    if (event.key === "Enter") {
      alert("Enter key pressed!");
    } else if (event.key === "Escape") {
      alert("Escape key pressed!");
    } else {
      console.log("Key pressed:", event.key);
    }
  }

  render() {
    return (
      <div>
        <h3>Keyboard Event – Class Component</h3>
        <input
          type="text"
          placeholder="Press Enter or Escape"
          onKeyDown={(e) => this.handleKeyDown(e)}
        />
      </div>
    );
  }
}

export default KeyDownExample;

Common Use Cases:
  • Detecting Enter or Escape key
  • Accessibility improvements
  • Custom input behavior
  • Form submission via keyboard

React supports almost all standard browser events. The key difference is how these events are written.


List of events

HTML Event React Event Category Description
onclickonClickMouseTriggered when an element is clicked.
ondblclickonDoubleClickMouseFires when an element is double-clicked.
onmousedownonMouseDownMouseOccurs when a mouse button is pressed.
onmouseuponMouseUpMouseOccurs when a mouse button is released.
onmouseoveronMouseOverMouseTriggered when the pointer enters an element.
onmouseoutonMouseOutMouseTriggered when the pointer leaves an element.
onmousemoveonMouseMoveMouseFires when the mouse moves within an element.
onmouseenteronMouseEnterMouseRuns when the mouse enters an element (no bubbling).
onmouseleaveonMouseLeaveMouseRuns when the mouse leaves an element (no bubbling).
onkeydownonKeyDownKeyboardTriggered when a key is pressed down.
onkeyuponKeyUpKeyboardTriggered when a pressed key is released.
onkeypressonKeyPressKeyboardTriggered when a character key is pressed (deprecated).
onchangeonChangeFormRuns when input value changes.
onsubmitonSubmitFormTriggered when a form is submitted.
oninputonInputFormFires immediately as the user types.
onresetonResetFormTriggered when a form is reset.
onfocusonFocusFocusRuns when an element gains focus.
onbluronBlurFocusRuns when an element loses focus.
onloadonLoadUITriggered when a resource finishes loading.
onerroronErrorUIRuns when an error occurs during loading.
oncopyonCopyClipboardTriggered when content is copied.
oncutonCutClipboardTriggered when content is cut.
onpasteonPasteClipboardTriggered when content is pasted.
ontouchstartonTouchStartTouchTriggered when a touch point starts.
ontouchendonTouchEndTouchTriggered when a touch point ends.
ontouchmoveonTouchMoveTouchTriggered when a touch point moves.
ontouchcancelonTouchCancelTouchTriggered when a touch is interrupted.
ondragonDragDragFires while an element is being dragged.
ondragstartonDragStartDragTriggered when dragging starts.
ondragendonDragEndDragTriggered when dragging ends.
ondragoveronDragOverDragRuns when a dragged item is over a target.
ondroponDropDragTriggered when a dragged item is dropped.

Summary

React events provide a structured and predictable way to handle user interactions across applications. Whether using functional components or class components, event handling follows the same principles.

Events act as the bridge between user behavior, state updates, and UI changes. Mastering React events makes it much easier to work with forms, conditional rendering, and routing in real-world projects.