Open In App

React Events

Last Updated : 15 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In React, events handle user interactions within components. They are similar to DOM events but offer a consistent interface across browsers. They are attached directly to JSX elements. React’s synthetic event system simplifies handling interactions, making it easier to build responsive UIs.

What is React Events?

React events are functions that get triggered in response to user interactions or other actions in the browser. They are similar to standard DOM events but have a consistent, cross-browser interface in React. React events use camelCase naming conventions and are attached to JSX elements as attributes.

Common examples of React events include

  • Using events like onChange or onInput to capture and process user input in text fields.
  • Utilizing onClick to run functions when users click buttons or links.
  • Using onSubmit to trigger logic when a form is submitted.
  • Working with onMouseOver, onMouseLeave, onKeyDown, or onKeyUp to provide interactivity based on mouse movements or keyboard input.

In HTML, an event is defined like this:

<button onclick="activateLasers()">Activate Lasers</button>

In React, the syntax changes to:

<button onClick={activateLasers}>Activate Lasers</button>

Notice that in React, event handlers like onClick are written in camelCase and are passed as function references (not function calls).

Commonly Used React Event Handlers

React Event

Description

onClick

This event is used to detect mouse clicks in the user interface.

onChange

This event is used to detect a change in the input field in the user interface.

onSubmit

This event fires on the submission of a form in the user interface and is also used to prevent the default behavior of the form.

onKeyDown

This event occurs when the user press any key from the keyboard.

onKeyUp

This event occurs when the user releases any key from the keyboard.

onMouseEnter

This event occurs when the ouse enters the boundary of the element

Adding React Events

React events are defined in camelCase, not lowercase. When setting events, you pass the event handler function, similar to passing props or attributes in JSX.

onClick={function}

Passing Arguments in React Events

In React Events, we pass arguments with the help of arrow functions. Like functions, we create parenthesis and pass arguments, but here, it is not possible; we have to use an arrow function to pass arguments.

onClick={()=>{function(argument)}}

React Event Object

React provides an event object that contains details about the event, such as type, target, value, and id. You can pass this event object to your function to handle events more effectively.

onClick={(event)=>{function(event)}}

Handling Events with State

Handling events with the state in React involves using event listeners (like onClick or onChange) to capture user interactions. These events trigger functions that update the component's state using useState. This enables dynamic and responsive UI updates based on user input or actions.

import React, { useState } from 'react';
const App = () => {
    const [text, setText] = useState('');

    const handleChange = (event) => {
        setText(event.target.value);
    };
    return (
        <div>
            <input type="text" value={text} onChange={handleChange} />
            <p>You typed: {text}</p>
        </div>
    );
};
export default App;

Output:

Animationkk
Handling Events with State

In this example

  • Import React and useState: Brings in useState for state management.
  • State Initialization: Defines text state with an empty string and a setter function, setText.
  • handleChangs: Updates the text state with the input's value whenever the user types.
  • Rendered Output: Renders an input field controlled by text and displays the typed value in real time.
  • Controlled Component: The input’s value is managed by the React state for synchronized updates.

Now let's see an example to understand the React Event properly: Implementation of Event Handler

import { useState } from "react";
import "./App.css";
function App() {
    const [inp, setINP] = useState("");
    const [name, setName] = useState("");
    const clk = () => {
        setName(inp);
        setINP("");
    };
    return (
        <div className="App">
            <h1>GeeksforGeeks</h1> \
            {name ? <h2>Your Name:{name}</h2> : null}
            <input
                type="text"
                placeholder="Enter your name..."
                onChange={(e) => setINP(e.target.value)}
                value={inp}
            />
            <button onClick={clk}>Save</button>{" "}
        </div>
    );
}
export default App;

Output

React Events Example - Output

In this example

  • The component uses useState to manage two states: inp for the input field’s value and name to store the user’s name once it’s submitted.
  • The input field’s value is controlled by inp. When the user types, onChange updates inp with the current input.
  • Clicking the “Save” button sets the name to the current input value and clears inp.
  • If the name is set, it displays a message with the user’s name; otherwise, it shows only the input field and the button.

React Events - FAQs

How do React events differ from native DOM events?

React events are synthetic events, which means they provide a consistent API across different browsers. They are optimized for performance using event delegation.

Why is bind(this) needed in class components?

In JavaScript, class methods are not bound to the instance by default. Using bind(this) ensures that this refers to the component instance inside event handlers.

How can I pass parameters to event handlers in React?

You can pass parameters using an arrow function or bind:

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

How do I prevent default behavior in React events?

Use event.preventDefault() inside the event handler:

Can I use event listeners like addEventListener in React?

Yes, but it's usually unnecessary because React provides built-in event handling. If needed, you can use componentDidMount():


Next Article

Similar Reads

three90RightbarBannerImg