MyInternships.in

State & Events

React Event Handling

React attaches events through camelCased props such as onClick, onChange and onSubmit, and you pass a function reference rather than a string. Under the hood React uses a single delegated listener at the root and wraps the native event in a synthetic event.


What is Event Handling in React?

React attaches events through camelCased props such as onClick, onChange and onSubmit, and you pass a function reference rather than a string. Under the hood React uses a single delegated listener at the root and wraps the native event in a synthetic event.

Why Event Handling matters

Events are how a user changes state. Getting the syntax right — reference not call, camelCase not lowercase — removes the most common "my button fires on page load" confusion.

Event Handling example

Passing a handler correctly
JSX
function ApplyButton({ jobId }) {
  function handleClick(e) {
    e.preventDefault();
    console.log('applying to', jobId);
  }

  return <button onClick={handleClick}>Apply</button>;   // reference
  // NOT onClick={handleClick()} — that calls it during render
}

How this works

onClick={handleClick} hands React the function to call later. onClick={handleClick()} calls it immediately during render and passes the return value, which is why the action appears to fire on load.

Passing arguments to a handler

JSX
{jobs.map(job => (
  <button key={job.id} onClick={() => onSave(job.id)}>Save</button>
))}

Wrap the call in an arrow function so it runs on click rather than during render. The arrow also closes over job.id from the map.

Key points to remember

  • Handler props are camelCased: onClick, onChange, onSubmit, onKeyDown, onMouseEnter.
  • e.preventDefault() stops default behaviour; e.stopPropagation() stops bubbling.
  • React 17 and later attach listeners to the root container, not to document.

Common mistakes with Event Handling

  • onClick={handleClick()} — calls on render.
  • onclick instead of onClick — a plain unknown DOM attribute that does nothing.
  • Forgetting preventDefault on a form submit, so the page reloads and state resets.

React Event Handling— Interview Questions & FAQs

Why does my onClick fire immediately when the page loads?+

You called the function instead of passing it: onClick={doThing()} runs during render. Pass onClick={doThing}, or onClick={() => doThing(arg)} when you need arguments.

Related React Topics

Keep learning with these closely related lessons.

Ready to use your React skills?

Find verified React internships and fresher developer jobs across India.

Browse React Internships