#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
State and Event Binding

Introduction to Events

Events in React are how components respond to what users do: clicking a button, typing in an input, submitting a form, hovering over a card or pressing a key. You attach a handler function to a JSX element with a camelCase prop such as onClick or onChange, and React calls that function when the event happens. Events are usually what trigger state changes, which then update what the user sees.

Attaching your first handler

Pass a function, not the result of calling it. React wraps the browser's native event in a SyntheticEvent object with the same familiar properties, like target, key and preventDefault(), and consistent behaviour across browsers.

function LikeButton() {
  function handleClick(event) {
    console.log('Clicked', event.currentTarget.textContent);
  }

  return <button onClick={handleClick}>Like</button>;
}

How React events differ from HTML attributes

Plain HTMLReact JSX
onclick="save()"onClick={save}
Lowercase attribute namescamelCase prop names
A string of codeA function reference
return false can cancel the defaultYou must call event.preventDefault()

Under the hood, React does not attach a listener to every element. It listens at the root of your app and dispatches events to the right handlers, which keeps things efficient even with many elements.

Passing extra data to a handler

Often you need to know which item was clicked. Wrap the call in an arrow function so it runs only when the event fires.

function TodoList({ todos, onDelete }) {
  return (
    <ul>
      {todos.map((todo) => (
        <li key={todo.id}>
          {todo.text}
          <button onClick={() => onDelete(todo.id)}>Delete</button>
        </li>
      ))}
    </ul>
  );
}

function SearchBox() {
  function handleKeyDown(event) {
    if (event.key === 'Enter') {
      console.log('Search for', event.target.value);
    }
  }
  return <input onKeyDown={handleKeyDown} placeholder="Search" />;
}

Here the parent passes onDelete as a prop. Naming props onSomething and handlers handleSomething is a widely used convention that makes the data flow easy to read.

The handler that runs on every render

The classic mistake is writing onClick={handleClick()} or onClick={onDelete(todo.id)}. The parentheses call the function immediately during rendering and pass its return value, usually undefined, as the handler. Clicks then do nothing, and if the function sets state, React may re-render in an endless loop and stop with a "Too many re-renders" error. Pass the function itself, or wrap it in an arrow.

Another frequent issue is forgetting event.preventDefault() on a form's onSubmit, which lets the browser reload the page and wipe your component state.

Events you will use most

  • onClick for buttons and clickable items.
  • onChange for inputs, selects and textareas; in React it fires on every keystroke.
  • onSubmit on forms.
  • onKeyDown for keyboard shortcuts.
  • onFocus and onBlur for validation when a field is entered or left.
  • onMouseEnter and onMouseLeave for hover effects.

Event handlers in React also bubble, just like DOM events. A click on a button inside a clickable card triggers both the button's and the card's onClick. Call event.stopPropagation() in the button's handler if the card action should not run, but use it only where that separation is really needed.

Where this leads

Handlers by themselves only log or call props. Their real power comes when they update state, so the component re-renders with new data. Keep handlers as named functions inside the component, pass them by reference, and use arrow wrappers only when you need to supply arguments.

Ready to master real-world web development?

Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.

Explore Course