DEV Community

Cover image for React Mastery Series – Day 9: Event Handling in React – Making Applications Interactive
Siva Samanthapudi
Siva Samanthapudi

Posted on

React Mastery Series – Day 9: Event Handling in React – Making Applications Interactive

Welcome back to the React Mastery Series!

In the previous article, we explored React Rendering and Component Lifecycle.

We learned:

  • What causes a component to re-render
  • How React reconciliation works
  • The difference between rendering and DOM updates
  • How lifecycle behavior is handled using Hooks

Now let's learn how React applications respond to user interactions.

Every modern application depends on events:

  • Clicking buttons
  • Typing into forms
  • Selecting options
  • Submitting data
  • Dragging and dropping elements
  • Keyboard shortcuts

React provides a powerful event system to handle all these interactions.


What is Event Handling?

Event handling is the process of responding to user actions in an application.

Examples:

User Action
     |
     ↓
Event Triggered
     |
     ↓
Event Handler Executes
     |
     ↓
State Updated
     |
     ↓
UI Re-renders
Enter fullscreen mode Exit fullscreen mode

Example:

A user clicks the "Transfer Money" button:

Click Button
     |
     ↓
Handle Click Event
     |
     ↓
Validate Data
     |
     ↓
Call API
     |
     ↓
Update UI
Enter fullscreen mode Exit fullscreen mode

Events in Traditional JavaScript vs React

Traditional JavaScript

const button =
document.getElementById("save");

button.addEventListener(
  "click",
  saveData
);
Enter fullscreen mode Exit fullscreen mode

You manually:

  • Find the DOM element
  • Attach event listeners
  • Manage updates

React

React attaches events directly inside JSX.

<button onClick={saveData}>
  Save
</button>
Enter fullscreen mode Exit fullscreen mode

React manages the event registration internally.


React Event Syntax

React events use:

  • camelCase naming
  • JSX expressions
  • Function references

HTML:

<button onclick="save()">
Save
</button>
Enter fullscreen mode Exit fullscreen mode

React:

<button onClick={save}>
Save
</button>
Enter fullscreen mode Exit fullscreen mode

Notice:

onclick  ❌
onClick  ✅
Enter fullscreen mode Exit fullscreen mode

Handling Click Events

Example:

function Button() {

  function handleClick() {
    console.log("Button clicked");
  }

  return (
    <button onClick={handleClick}>
      Click Me
    </button>
  );
}
Enter fullscreen mode Exit fullscreen mode

When the user clicks:

Click
 |
 ↓
handleClick()
 |
 ↓
Execute Logic
Enter fullscreen mode Exit fullscreen mode

Passing Functions vs Calling Functions

A very common beginner mistake.

Incorrect

<button onClick={handleClick()}>
  Save
</button>
Enter fullscreen mode Exit fullscreen mode

This executes immediately during rendering.


Correct

<button onClick={handleClick}>
  Save
</button>
Enter fullscreen mode Exit fullscreen mode

React calls the function only when the event occurs.


Passing Arguments to Event Handlers

Sometimes you need to pass additional information.

Example:

function deleteUser(id) {
  console.log(id);
}
Enter fullscreen mode Exit fullscreen mode

Incorrect:

<button onClick={deleteUser(10)}>
Delete
</button>
Enter fullscreen mode Exit fullscreen mode

Correct:

<button
  onClick={() => deleteUser(10)}
>
Delete
</button>
Enter fullscreen mode Exit fullscreen mode

The arrow function delays execution until the click happens.


The Event Object

React automatically provides an event object.

Example:

function handleClick(event) {

  console.log(event);

}
Enter fullscreen mode Exit fullscreen mode

Usage:

<button onClick={handleClick}>
Click
</button>
Enter fullscreen mode Exit fullscreen mode

The event object contains information about:

  • Target element
  • Event type
  • Mouse position
  • Keyboard details
  • Form information

Synthetic Events in React

React does not directly use browser events.

Instead, React provides a wrapper called SyntheticEvent

Example:

function handleClick(event) {

 console.log(event.type);

}
Enter fullscreen mode Exit fullscreen mode

Output:

click
Enter fullscreen mode Exit fullscreen mode

Why does React use Synthetic Events?

Benefits:

✅ Cross-browser consistency
✅ Same API across browsers
✅ Better event management
✅ Performance optimizations

Your code behaves consistently across different environments.


Common Mouse Events

React supports many mouse events:

Event Purpose
onClick Mouse click
onDoubleClick Double click
onMouseEnter Mouse enters element
onMouseLeave Mouse leaves element
onMouseMove Mouse movement

Example:

<div
 onMouseEnter={() =>
 console.log("Hovered")
 }
>
 Hover Me
</div>
Enter fullscreen mode Exit fullscreen mode

Keyboard Events

Keyboard interactions are common in search boxes and forms.

Examples:

<input
 onKeyDown={(event) =>
 console.log(event.key)
 }
/>
Enter fullscreen mode Exit fullscreen mode

If user presses:

Enter
Enter fullscreen mode Exit fullscreen mode

Output:

Enter
Enter fullscreen mode Exit fullscreen mode

Common keyboard events:

  • onKeyDown
  • onKeyUp

Form Handling in React

Forms are one of the most important parts of frontend development.

Example:

function LoginForm(){

function handleSubmit(event){

 event.preventDefault();

 console.log("Submitted");

}

return (

<form onSubmit={handleSubmit}>

<button>
Login
</button>

</form>

);

}
Enter fullscreen mode Exit fullscreen mode

Preventing Default Behavior

HTML forms refresh the page by default after submission.

React applications usually prevent this.

Example:

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

This allows React to handle the form submission without refreshing the browser.

Common use cases:

  • Login forms
  • Registration forms
  • Search forms
  • Payment forms

Controlled Components

React forms usually follow a pattern called Controlled components pattern.

The React state becomes the single source of truth.

Example:

function Login(){

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

return (

<input
 value={email}
 onChange={(e)=>
 setEmail(e.target.value)}
/>

);

}
Enter fullscreen mode Exit fullscreen mode

Flow:

User Types
    |
    ↓
onChange Event
    |
    ↓
Update State
    |
    ↓
Component Re-renders
    |
    ↓
Updated Value Displayed
Enter fullscreen mode Exit fullscreen mode

Handling Multiple Inputs

Real applications usually contain multiple fields.

Example:

const [form,setForm] =
useState({
 email:"",
 password:""
});
Enter fullscreen mode Exit fullscreen mode

Updating:

setForm({
 ...form,
 email:e.target.value
});
Enter fullscreen mode Exit fullscreen mode

The spread operator preserves existing values.


Event Bubbling

Events can travel from child elements to parent elements.

Example:

<div onClick={parentClick}>

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

</div>
Enter fullscreen mode Exit fullscreen mode

Clicking the button triggers:

Button Click
      |
      ↓
Parent Click
Enter fullscreen mode Exit fullscreen mode

This is called:

Event Bubbling


Stopping Event Propagation

Sometimes you don't want the event to reach the parent.

Use:

event.stopPropagation();
Enter fullscreen mode Exit fullscreen mode

Example:

function buttonClick(event){

event.stopPropagation();

}
Enter fullscreen mode Exit fullscreen mode

Real-World Example: Banking Application

Consider a fund transfer screen:

Enter Amount
      |
      ↓
onChange Event
      |
      ↓
Update State
      |
      ↓
Click Transfer Button
      |
      ↓
onClick Event
      |
      ↓
Validate Data
      |
      ↓
Call API
      |
      ↓
Show Success Message
Enter fullscreen mode Exit fullscreen mode

Every user interaction is managed through React events.


Common Mistakes

Calling Functions Immediately


onClick={save()}
Enter fullscreen mode Exit fullscreen mode


onClick={save}
Enter fullscreen mode Exit fullscreen mode

Mutating State Directly


count++;
Enter fullscreen mode Exit fullscreen mode


setCount(count+1);
Enter fullscreen mode Exit fullscreen mode

Forgetting preventDefault()

Forms may refresh unexpectedly.


Creating Too Many Inline Functions

Example:

<button
onClick={() =>
handleDelete(id)
}
>
Delete
</button>
Enter fullscreen mode Exit fullscreen mode

This is acceptable for small cases.

For large lists, consider optimization techniques later in this series.


Best Practices

  • Keep event handlers meaningful.
  • Move complex logic into separate functions.
  • Use controlled components for forms.
  • Prevent unnecessary re-renders.
  • Use semantic event names.
  • Keep components focused.

Key Takeaways

Today, we learned:

✅ React handles events using JSX syntax.
✅ Event names use camelCase.
✅ Functions should be passed, not immediately executed.
✅ React uses Synthetic Events for consistency.
✅ Forms are commonly managed using controlled components.
✅ Event propagation can be controlled using stopPropagation.


Coming Next 🚀

In Day 10, we will explore:

Conditional Rendering in React – Building Dynamic Interfaces

We will learn:

  • Rendering elements conditionally
  • if/else patterns
  • Ternary operators
  • Logical AND rendering
  • Conditional components
  • Authentication-based UI
  • Real-world dashboard examples

Conditional rendering is one of the most frequently used concepts in production React applications.

Happy Coding! 🚀

Top comments (0)