Menu

Handling Events in React: onClick, onChange & More

Handling Events in React

What Are Events?

Events are user actions: clicks, typing, form submissions, and mouse movements. React handles them with camelCase attributes that take a function.

Syntax

jsx

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

Common Events

Event

Fires when

onClickAn element is clicked
onChangeAn input's value changes
onSubmitA form is submitted
onMouseEnterThe pointer enters an element
onKeyDownA key is pressed
onBlurAn element loses focus

Example

src/components/CourseFilter.jsx

jsx

import { useState } from "react";

function CourseFilter() {

const [searchText, setSearchText] = useState("");

const [showCompleted, setShowCompleted] = useState(false);

function handleSearchChange(event) {

setSearchText(event.target.value);

}

function handleToggle() {

setShowCompleted(!showCompleted);

}

function handleClear() {

setSearchText("");

}

return (

<div>

<input

type="text"

value={searchText}

onChange={handleSearchChange}

placeholder="Search courses"

/>

<button onClick={handleClear}>Clear</button>

<button onClick={handleToggle}>

{showCompleted ? "Hide completed" : "Show completed"}

</button>

<p>Searching for: {searchText}</p>

</div>

);

}

export default CourseFilter;

How It Works

  • onChange={handleSearchChange}: pass the function, do not call it. Note there are no parentheses.
  • event.target.value: the current text in the input. React passes an event object to every handler.
  • setShowCompleted(!showCompleted): flips a boolean, a common toggle pattern.
  • The button label itself changes based on state, using a ternary.

Passing Arguments to Handlers

If a handler needs an argument, wrap it in an arrow function:

jsx

// Wrong — this calls the function immediately during render

<button onClick={handleDelete(courseId)}>Delete</button>

// Correct — this passes a function that will call it later

<button onClick={() => handleDelete(courseId)}>Delete</button>

This is one of the most common beginner bugs in React. Without the arrow function, the code runs on every render instead of on click, often causing an infinite loop.

Output

Typing in the box updates the text below it instantly. The toggle button's label switches between "Show completed" and "Hide completed."


ReactJS Tutorial



Learn via Video Course

React.js for Beginners: Build Modern Web Applications with React Logo

React.js for Beginners: Build Modern Web Applications with React

6 hrs



Get in Touch For Details