Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

To handle an event in React, define a function and pass it to a camelCase event prop in JSX—for example, <button onClick={handleClick}>. React calls the function when the interaction occurs and passes it an event object, usually named e. The key distinction is to pass the function, not call it during render: use onClick={handleClick}, not onClick={handleClick()}.

This guide covers click and keyboard handlers, controlled inputs, form submission in all React versions, React 19 form Actions, event bubbling, and common bugs. The examples use React DOM in the browser.

How do I add an event handler in React?

Declare a function in your component, put the interaction logic in it, and pass the function to the JSX element’s event prop. React event props use camelCase, such as onClick and onChange; unlike an HTML inline handler, the prop receives a function rather than a string.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
export default function Button() {
  function handleClick() {
    alert('You clicked me!');
  }

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

When the user clicks the button, React invokes handleClick. By convention, handler functions often start with handle followed by the event, while handler props on custom components often start with on followed by a capital letter. For example, a component might accept an onPlayMovie prop and pass it to a button’s onClick.

Popular on Amazon
Silkland 40Gbps USB C 90 Degree Right Angle Adapter 2 Pack, 240W USB4 | Male to Female Extender, 8K@60Hz, Thunderbolt 4/3, Steam Deck, ROG Ally, MacBook, Switch 2, iPhone 18/17/16/15, Quest 3 VR
  • 【90 Degree Full Function USB C Adapter】Supports the latest USB4 standard for up to 40Gbps of bandwidth, 8K video support, and up to 240W Fast charging; Support USB PD 3.1 Extended Power Range (EPR) including 140W, 180W and 240W. Your productivity is easily doubled. *Warm Tip: For the best fit, please make sure the USB-C port is fully exposed; thick or bulky cases may affect compatibility.
  • 【Reliable Quality】Made from high-quality, scratch-resistant aluminum alloy, delicate metal frame. get excellent wear resistance and heat dissipation. Non-Slip Design for easier insertion and removal.
  • 【Small and portable】Ultra thin size, ultra compact design, a petite physique that matches the minimalist design of your modern laptops. Coming with a slim figure that won't block the port next to the one it's plugged into.
  • 【Compatibility】Widely work with most usb c, thunderbolt 4/3 devices. Compatibilit for ROG Ally, Steam Deck, Switch, MacBook Pro, Quest 3 VR headset, Surface Book 2, iPhone 18/17/16/15, Samsung Galaxy S23/S22/S21, Note 20/10, Google Pixel, ChromeBook, etc.
  • 【Excellence Customer Support】If you experience any issues or cable failure, simply reach out to our dedicated customer service team. We provide a prompt response within 18 hours, providing you with the necessary technical support to resolve any concerns.

A short handler can also be written inline:

<button onClick={() => alert('You clicked me!')}>
  Click me
</button>

React’s current documentation treats named functions and inline functions as valid alternatives. A named function is easier to read when the logic grows or is reused; an inline arrow can keep a short, local action close to its element. An inline arrow creates a new function on each render, which is usually not a correctness issue; it may matter later when passing callbacks to memoized children. Consider useCallback only when there is a specific optimization reason.

Why does my onClick run when the page loads?

The handler was probably called while React was rendering. JSX expressions are evaluated immediately, so onClick={handleClick()} runs handleClick as the component renders, then passes its return value rather than the function to React.

// Correct: pass the function for React to call later
<button onClick={handleClick}>Save</button>

// Incorrect: calls the function during render
<button onClick={handleClick()}>Save</button>

The same rule applies to inline work. onClick={alert('Saved')} evaluates the alert during render; onClick={() => alert('Saved')} waits until the click. Calling a state setter in JSX, such as onClick={setCount(count + 1)}, also updates state during render and can trigger a “Too many re-renders” error. Pass a function instead.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What does the React event object contain?

React passes an event object to the handler as its first argument. You will often see it named e; it provides useful details about the interaction and methods for controlling browser behavior or event propagation.

function handleClick(e) {
  console.log(e.type);          // for example, "click"
  console.log(e.currentTarget); // the element with this handler
}

Older React documentation calls this wrapper a SyntheticEvent. It presents a consistent interface across browsers and includes familiar event properties and methods, such as target, currentTarget, type, key, preventDefault(), and stopPropagation(). In most application code, use the event object React gives the handler rather than depending on browser-specific details.

e.nativeEvent exposes the underlying browser event, but the mapping between React events and native events is not a public contract and may change. For example, a React onMouseLeave event can correspond to a native mouseout event. Prefer React’s event properties unless native-event details are genuinely needed.

How do I prevent a form from reloading in React?

Put onSubmit on the <form> and call e.preventDefault() in its handler if you want to handle the submission without the browser’s normal navigation or page refresh. This pattern works across React versions.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Also popular on Amazon
Sale
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display | 85W Max PD, 1 Powered USB-C 5Gbps & 2 Powered USB-A 3.0 5Gbps Data Ports, for MacBook Pro, MacBook Air, Dell and More (Black)
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
export default function Signup() {
  function handleSubmit(e) {
    e.preventDefault();
    const formData = new FormData(e.currentTarget);
    const email = formData.get('email');
    alert(`Submitting ${email}`);
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Email
        <input name="email" type="email" required />
      </label>
      <button type="submit">Send</button>
    </form>
  );
}

The browser normally submits the form to the current URL and refreshes the page. Calling preventDefault() cancels that browser action so your handler can process the data. Attach submission logic to the form rather than only to the button: a form can also be submitted by pressing Enter in a field, and native validation such as required and type="email" can run before submission.

Returning false from a React handler does not cancel the browser’s default behavior or stop propagation. Use the relevant method explicitly.

What is the difference between preventDefault and stopPropagation in React?

preventDefault() cancels the browser’s default action; stopPropagation() prevents the event from continuing to ancestor handlers. They do different jobs, and calling one does not do the other.

Method What it changes Example
e.preventDefault() Whether the browser performs its default action Stop a form from navigating or a link from following its URL while handling it yourself
e.stopPropagation() Whether the event reaches parent handlers Keep a button click inside a clickable card from also triggering the card’s handler

For example, a button inside a toolbar can run its own action and stop the click from triggering the toolbar’s parent handler:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
function handleButtonClick(e) {
  e.stopPropagation();
  saveItem();
}

<div onClick={openToolbarItem}>
  <button onClick={handleButtonClick}>Save</button>
</div>

Use preventDefault() when the browser action is the problem; use stopPropagation() when an ancestor handler should not also respond. If you want a child to notify a parent, an explicit callback prop can be easier to follow than relying on bubbling.

How does event bubbling and capture work in React?

Most React events propagate: the target’s handler runs, followed by handlers on its ancestors. You can stop that upward propagation in a handler, or use a capture-phase prop when an ancestor needs to observe the event before it reaches the target.

For a click, the usual order is:

  1. Capture handlers run down the tree, from ancestor toward the target; for example, onClickCapture.
  2. The target element’s onClick handler runs.
  3. Bubbling onClick handlers run back up through the ancestors.
<div onClickCapture={() => console.log('capture')}
     onClick={() => console.log('parent bubble')}>
  <button onClick={() => console.log('button')}>Click</button>
</div>

Capture is useful when an ancestor must see an interaction even if a descendant later stops propagation, such as in some analytics or routing logic. Most interface code can use ordinary bubbling handlers instead. React’s documented exception is onScroll, which works on the JSX element where it is attached rather than bubbling to a parent. Mouse and pointer enter/leave events also have special propagation behavior rather than ordinary bubbling.

Also popular on Amazon
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter | 85W Max PD, 2 USB 3.0 & 1 USBC Data Ports, SD/TF Card Reader, for Laptops/Mac and Other Type C Devices (Charger Not Included)
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

How do I handle text input with onChange?

For a controlled text input, store its value in state, provide that state through value, and update it from onChange. React’s onChange for text fields fires as the user types, allowing the displayed value and component state to stay in sync.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import { useState } from 'react';

export default function NameField() {
  const [name, setName] = useState('');

  function handleChange(e) {
    setName(e.target.value);
  }

  return (
    <label>
      Name
      <input value={name} onChange={handleChange} />
    </label>
  );
}

In HTML, the native change event for a text field generally fires after the value is committed, often when the field loses focus. React’s onChange is designed to fire on each keystroke for text inputs. If you set value but omit an onChange handler that updates it, the field will not behave as an editable controlled input.

Use the event target that matches the control. For a text field, read e.target.value; for a checkbox, read e.target.checked. For example:

function handleCheckboxChange(e) {
  setSubscribed(e.target.checked);
}

How do I respond to a key press?

Use onKeyDown and inspect e.key for keyboard shortcuts or actions tied to a particular key. For new code, prefer onKeyDown over the deprecated onKeyPress.

function handleKeyDown(e) {
  if (e.key === 'Escape') {
    closeDialog();
  }
}

<input onKeyDown={handleKeyDown} />

How do I pass a parameter to an onClick handler?

Wrap the call in an arrow function so React invokes it on the click, then pass the value you need. If the handler also needs the event object, pass it explicitly.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<button onClick={() => deleteTask(task.id)}>
  Delete
</button>

<button onClick={(e) => deleteTask(task.id, e)}>
  Delete and inspect event
</button>

In a function component, handlers are closures and can refer to values from the component’s render. Do not write onClick={deleteTask(task.id)} unless you intentionally want that function to run during render.

How do class components handle this in event handlers?

Class component methods are not automatically bound to the component instance. If a method reads this, bind it in the constructor or define it as an arrow class field; function components do not have this binding issue.

Also popular on Amazon
BENFEI USB C Hub 5-in-1 with 4K HDMI(Certified), 100W Power Delivery, 3 USB-A, Silicone Cable, Aluminum Case Compatible with MacBook Pro/Air, iPad Pro, iMac, iPhone 15 Pro/Pro Max, XPS, Thinkpad
  • Portable and powerful USB-C HUB: BENFEI USB Type-C HUB, with super-soft and knot-free silicone woven design cable, meets most mobile office needs. Compact, lightweight, stylish, and powerful portable USB C Hub equipped with 1 x HDMI port, 1 x 100W charging, and 3 x USB ports. 18-month warranty, 24-hour response, to ensure you feel at ease when using our product.
  • Design centered on comfort and reliability: Thanks to BENFEI's end-to-end in-house cable production capability, in-house PCBA and assembly capability, using the industry's most advanced silicone woven design and process, 20cm cable in length, no knots, super-soft, the HUB is easy to use in all scenarios: laptop, tablet, stand etc. Super-soft, 25000+ life cycles, to meet your daily carrying and office needs.
  • 100W Charging: Support up to 90W USB C pass-through charging via Type-C port to keep your laptop powered. 10W is reserved for other interface operations. No data and video function on the Type-C port.
  • 4K HDMI Display: The HDMI port supports media display at resolutions up to 4K 30Hz, keeping every incredible moment detailed and ultra vivid. Please note that the C port of the Host device needs to support video output.
  • Transfer Files in Seconds: Transfer files and from your laptop at speeds up to 10 Gbps with USB A 3.2 port. Extra 2 USB A 2.0 ports are perfectly for your keyboards and mouse.
class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(state => ({ isOn: !state.isOn }));
  }

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

Another class pattern is an arrow class field, such as handleClick = () => { ... }, which retains the instance as this. An inline arrow like onClick={() => this.handleClick()} also works, but creates a callback during each render and can matter when passing callbacks to memoized children.

Do I need addEventListener in React?

For elements rendered by React, usually not: attach the event prop in JSX when rendering the element. A button click, for instance, belongs on <button onClick={handleClick}>, not on a later manual listener added to that button’s DOM node.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Global targets such as window or document are different because they are not JSX elements in your component tree. If you add a listener for a global event in an effect, remove it in the effect’s cleanup so it does not remain after the component no longer needs it.

What changed about SyntheticEvent and event.persist()?

React stopped pooling SyntheticEvent objects in React 17, so e.persist() does nothing in current React versions. Older tutorials that tell you to call it before using an event asynchronously are outdated.

You can read or retain the event object without calling persist(). If an older code example includes the call, it can be removed; it is retained as a no-op for compatibility.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Should I use onSubmit or a React 19 form action?

Use onSubmit with e.preventDefault() when you want the submit event and a pattern that works in every React version. In React 19, a function passed to a form’s action is the preferred form-submission API for an Action-based workflow.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Approach Handler receives Prevent default manually? Useful when
onSubmit={handleSubmit} The submit event Yes, if handling submission without browser navigation You need the event or want a version-compatible submit handler
action={search} in React 19 A FormData object No You want React’s form Action behavior, including transition handling

React 19 became available on npm on December 5, 2024, according to the React 19 release announcement. A function passed to action receives form data from named fields, runs in a Transition, and resets uncontrolled fields after a successful submission. React also makes pending state available to descendants through useFormStatus from react-dom; errors are sent to the nearest Error Boundary.

Also popular on Amazon
𝟒𝐏𝐚𝐜𝐤 𝐔𝐩𝐠𝐫𝐚𝐝𝐞𝐝 USB to USB C Adapter,Type-C Female to A Male Charger Converter for iPhone 18 Charger,iWatch Ultra SE 9 10,iPhone 17 Pro Max 16 15 14,Samsung S25,AirPods,iPad,Car,Xbox
  • 【Read before You Buy】 Note: This adapter is USB 2.0 version and cannot transmit HDM, VGA, or other video signals. Nevertheless, they are fully capable of charging devices,duplicating files, and can be seamlessly integrated with USB-C earphones, wireless network adapters, and SD card adapters.
  • 【Easy to Use and Safe】Thanks to modern manufacturing techniques, we've made these adapters sufficiently compact so that they can remain inserted in your device without noticeable protrusion or inconvenience. This means you don't have to constantly plug and unplug them, reducing the likelihood of wear and misalignment, and making them more convenient to carry around.
  • 【Reliable Quality】Engineered for enhanced durability, durable aluminum alloy shell material,get excellent wear resistance and heat dissipation,the male USB C and female USB connectors & the male USB and female USB C connectors are designed to be plugged and unplugged up to 20000 times. Provides data transfer, device charging, memory space expansion, and additional computer peripherals.
  • 【Think more for you】Do you need to connect a USB-C-enabled device to an odd device that only has USB-A ports? Then these USB-A male to USB-C female adapters are made for you.Simply insert the adapter into the USB-A port on the device, and you can instantly connect your USB-C device to the device that originally didn't have the correct connection port.
  • 【Trusted xiwxi Quality and Service】As a responsible brand seller, you will receive xiwxi's 12-month Quality assurance and lifetime friendly customer service, you're not just buying a product,you're investing in peace of mind with all-round quality and exceptional customer service.
export default function Search() {
  function search(formData) {
    const query = formData.get('query');
    alert(`You searched for '${query}'`);
  }

  return (
    <form action={search}>
      <input name="query" />
      <button type="submit">Search</button>
    </form>
  );
}

The input needs a name so its value appears in the submitted FormData. This example is uncontrolled: it does not need a React value prop or onChange state handler. If a form has both a function action and an onSubmit handler, React runs the action after onSubmit unless that handler calls e.preventDefault().

React 19 also introduced related form and Action APIs, including useActionState for Action state and useOptimistic for optimistic UI. The React Team’s release notes explain the broader set of changes in the React 19 announcement; the current form reference documents the submission behavior and options.

What should I check when a React event handler is not working?

Most event bugs come from calling a handler too early, using the wrong event method, or making an interactive element harder to operate than necessary. Check the prop and element before adding more event code.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • For a DOM event prop, use the React camelCase name, such as onClick, rather than lowercase onclick.
  • Pass a function: onClick={handleClick}. Use a wrapper when you need arguments.
  • Use preventDefault() to cancel a browser action and stopPropagation() to block ancestor handlers; neither replaces the other.
  • Put submit logic on <form onSubmit> rather than only on the submit button’s click handler, so keyboard submission is handled too.
  • For a controlled input, pair value with an onChange handler that updates state.
  • Use a real <button> for an action instead of a clickable <div>, preserving built-in keyboard activation and button semantics.

For the current event mental model, see React’s Responding to Events guide. For form Actions and the form API, use the React form reference.

Frequently Asked Questions

What is e.currentTarget in a React event?

It identifies the element whose handler is currently running. This differs from e.target, which identifies the element where the event originated; in a click on an icon inside a button, the target may be the icon while the current target is the button.

Can a custom React component have an onClick prop?

Yes. A custom component can accept a callback prop such as onPlayMovie and pass it to an element inside its implementation. React does not automatically attach a custom component’s prop to a DOM node; the component must forward or invoke it.

Can I use onFocus and onBlur on elements other than inputs?

Yes. React supports focus and blur handlers on DOM elements beyond form controls, which can be useful for managing focus within a component or detecting when focus leaves a region.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Is onScroll handled by a parent React element?

No. React’s onScroll handler only runs on the JSX element to which it is attached, unlike most React events that propagate through ancestors.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply. Prices as of December 6, 2026 10:01 am GMT.