Labs ICT
Pro Login

Event Handling

Responding to user interactions.

Event Handling Basics

You've got components, props, and state — but how do you make your app respond to user actions? Event handling. It's how you make buttons clickable, forms submittable, and inputs interactive. Without events, your UI would just sit there staring at you.

In React, event handling works just like it does in plain HTML, but with a twist. You pass a function to the event handler instead of a string. This gives you full control over what happens when the user clicks, types, or submits something.

Common Event Handlers

The most common events you'll use are onClick, onChange, and onSubmit. Each one has a specific job. Click events fire when a user clicks. Change events fire when an input value changes. Submit events fire when a form is submitted.

You define a function, then pass it to the event handler. React takes care of connecting the dots. It's clean, simple, and gets the job done.

function SearchBox() {
  function handleSearch(query) {
    console.log("Searching for:", query);
  }

  return (
    <div>
      <input
        onChange={(e) => handleSearch(e.target.value)}
        placeholder="Search..."
      />
      <button onClick={() => handleSearch("react")}>
        Search
      </button>
    </div>
  );
}
Try it Yourself →

Preventing Default Behavior

Sometimes you want to stop the browser from doing its default thing. Like when a form submits — by default, the page refreshes. That's not what you want in a React app. You handle the submission yourself.

Every event handler in React gives you an event object. Call e.preventDefault() on it, and you stop the browser's default action. This is essential for forms, links, and any situation where you want React to take control.

function LoginForm() {
  function handleSubmit(e) {
    e.preventDefault();
    console.log("Form submitted without page refresh!");
  }

  return (
    <form onSubmit={handleSubmit}>
      <input type="email" placeholder="Email" />
      <button type="submit">Log In</button>
    </form>
  );
}
Try it Yourself →