Lesson 21 of 60 – React Events
35%

React Events

React Events are used to respond to actions performed by users, such as clicking a button, typing in an input field, submitting a form, moving the mouse, or pressing a keyboard key.

Note: React uses event handlers such as onClick, onChange, onSubmit, and onMouseOver to respond to user interactions.

1. What are Events?

An event is an action that happens in the browser. For example, when a user clicks a button, a click event occurs.

Common user events include:

  • Clicking a button
  • Typing text
  • Submitting a form
  • Moving the mouse
  • Pressing a keyboard key
  • Focusing an input
  • Changing a form value

2. Events in React

React provides event handlers through JSX attributes.

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

Here, onClick tells React which function should run when the button is clicked.

3. The onClick Event

The onClick event is used when an element is clicked.

function App() {

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

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

}

4. Event Handler Function

An event handler is a function that runs when a particular event occurs.

function handleClick() {

    console.log("Button was clicked");

}

The function can then be assigned to an event.

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

5. Calling an Event Handler

Pass the function itself to the event handler.

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

Do not call the function while rendering:

<!-- Avoid this -->

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

Using handleClick allows React to call the function when the event occurs.

6. Inline Event Handler

An event handler can also be written directly inside JSX.

function App() {

    return (
        <button
            onClick={() => alert("Hello React")}
        >
            Click Me
        </button>
    );

}

7. Passing an Event Function

A function can be defined separately and passed to the event.

function App() {

    function showMessage() {

        alert("Welcome to React!");

    }

    return (
        <button onClick={showMessage}>
            Show Message
        </button>
    );

}

8. onChange Event

The onChange event is commonly used with form inputs.

function App() {

    function handleChange(event) {

        console.log(event.target.value);

    }

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

}

9. Reading Input Values

The event object provides information about the element that triggered the event.

function handleChange(event) {

    console.log(event.target.value);

}

The value property contains the current input value.

10. The onSubmit Event

The onSubmit event is used when a form is submitted.

function App() {

    function handleSubmit(event) {

        event.preventDefault();

        alert("Form submitted!");

    }

    return (
        <form onSubmit={handleSubmit}>

            <input type="text" />

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

        </form>
    );

}

11. preventDefault()

Forms normally reload or navigate the page when submitted. preventDefault() prevents the browser's default action.

function handleSubmit(event) {

    event.preventDefault();

    console.log("Form submitted");

}

12. Mouse Events

React supports several mouse-related events.

  • onClick
  • onDoubleClick
  • onMouseEnter
  • onMouseLeave
  • onMouseOver
  • onMouseOut
  • onMouseDown
  • onMouseUp

13. onMouseEnter Event

The onMouseEnter event runs when the mouse pointer enters an element.

function App() {

    function handleMouseEnter() {

        console.log("Mouse entered");

    }

    return (
        <div onMouseEnter={handleMouseEnter}>

            Move the mouse here

        </div>
    );

}

14. onMouseLeave Event

The onMouseLeave event runs when the mouse pointer leaves an element.

function App() {

    function handleMouseLeave() {

        console.log("Mouse left");

    }

    return (
        <div onMouseLeave={handleMouseLeave}>

            Move the mouse away

        </div>
    );

}

15. Keyboard Events

React also supports keyboard events.

  • onKeyDown
  • onKeyUp
  • onKeyPress is an older event and is generally avoided in modern code.
function App() {

    function handleKeyDown(event) {

        console.log(event.key);

    }

    return (
        <input
            onKeyDown={handleKeyDown}
        />
    );

}

16. Reading Keyboard Keys

The event object provides information about which key was pressed.

function handleKeyDown(event) {

    console.log(
        "Pressed:",
        event.key
    );

}

For example, pressing Enter can produce Enter as the key value.

17. Event Object

React passes an event object to an event handler when the event occurs.

function handleClick(event) {

    console.log(event);

}

The event object contains useful information about the event and the element involved.

18. event.target

The event.target property refers to the element that triggered the event.

function handleClick(event) {

    console.log(event.target);

}

It can be useful when working with buttons, inputs, and other interactive elements.

19. Event Handler with Parameters

If an event handler needs an additional value, use an arrow function.

function showStudent(name) {

    alert(name);

}

function App() {

    return (
        <button
            onClick={() => showStudent("Rahul")}
        >
            Show Student
        </button>
    );

}

20. Event Handler with Props

Event handler functions can also be passed from a parent component through props.

function Button({ onClick }) {

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

}

21. Parent Event Handler

function App() {

    function handleClick() {

        alert("Clicked from parent");

    }

    return (
        <Button
            onClick={handleClick}
        />
    );

}

This allows the child button to trigger logic defined in the parent.

22. Events and State

Events are often used to update React state.

import { useState } from "react";

function Counter() {

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

    function increase() {

        setCount(count + 1);

    }

    return (
        <div>

            <p>
                Count: {count}
            </p>

            <button onClick={increase}>
                Increase
            </button>

        </div>
    );

}

23. Multiple Event Handlers

A component can have multiple event handlers.

function App() {

    function handleClick() {
        console.log("Clicked");
    }

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

    return (
        <button
            onClick={handleClick}
            onMouseEnter={handleMouseEnter}
        >
            Button
        </button>
    );

}

24. Events on Different Elements

Events can be attached to many HTML elements.

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

<input onChange={handleChange} />

<form onSubmit={handleSubmit}>
    ...
</form>

<div onMouseEnter={handleMouseEnter}>
    Hover
</div>

25. React Event Naming

React event names use camelCase.

Correct:

onClick
onChange
onSubmit
onMouseEnter
onKeyDown

HTML traditionally uses lowercase event attributes such as onclick, but React uses camelCase names.

26. Events and Forms

React events are commonly used for interactive forms.

function Login() {

    function handleSubmit(event) {

        event.preventDefault();

        console.log("Login submitted");

    }

    return (
        <form onSubmit={handleSubmit}>

            <input
                type="text"
                placeholder="Username"
            />

            <input
                type="password"
                placeholder="Password"
            />

            <button type="submit">
                Login
            </button>

        </form>
    );

}

27. Common Event Mistake

A common mistake is calling the event handler immediately during rendering.

Incorrect:

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

Correct:

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

For a function that needs parameters, use an arrow function.

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

28. React Events and User Interaction

Events make React applications interactive.

  • Buttons can respond to clicks.
  • Inputs can respond to changes.
  • Forms can respond to submissions.
  • Elements can respond to mouse actions.
  • Inputs can respond to keyboard actions.
  • Events can update component state.
  • Events can call functions passed through props.

29. Complete React Events Example

import { useState } from "react";

function App() {

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

    function handleChange(event) {

        setName(event.target.value);

    }

    function handleClick() {

        alert("Hello " + name);

    }

    return (
        <div>

            <h2>
                React Events
            </h2>

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

            <br />
            <br />

            <button onClick={handleClick}>
                Say Hello
            </button>

        </div>
    );

}

export default App;

This example uses onChange to read input and onClick to respond to a button click.

30. React Events Best Practices

  • Use camelCase event names such as onClick.
  • Pass event handler functions correctly.
  • Use arrow functions when parameters are required.
  • Use the event object when event information is needed.
  • Use preventDefault() when appropriate for forms.
  • Keep event handler functions clear and focused.
  • Use state when an event needs to change displayed data.
  • Pass event handlers through props when child components need them.
  • Avoid unnecessary inline logic for complex event handling.
  • Choose the appropriate event for each user interaction.

📌 Key Points

  • React events allow applications to respond to user actions.
  • onClick handles click events.
  • onChange is commonly used with input fields.
  • onSubmit handles form submission.
  • Mouse and keyboard events are also supported.
  • Event handlers are JavaScript functions.
  • React event names use camelCase.
  • The event object provides information about the event.
  • event.target identifies the element involved in the event.
  • Events are commonly combined with state to create interactive applications.

🧠 Quick Quiz

Question: Which React event is commonly used to handle a button click?