Handling Events

Handling Events in React

Handling Events in React

In React, handling events is much like how it's done in regular HTML. But, there are a few differences. You use camelCase for event names in React. This is instead of lowercase.

1. Event Handler Syntax

Example:

HTML: <button onclick="handleClick()">Click me</button>

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

You do not use a string to specify the event handler in React. Instead, directly pass the function reference.


function App() {
  function handleClick() {
    alert('Button clicked!');
  }

  return <button onClick={handleClick}>Click Me</button>;
}

    

2. Synthetic Events

React utilizes Synthetic Events. They are employed for handling user interactions. These events are essentially coverings for native browser events. This ensures consistency of operation across all browsers.

What does this indicate?

No need to be concerned about browser-specific idiosyncrasies. This is especially true when handling events inside React. React establishes a consistent behavior for events.


function App() {
  function handleInputChange(event) {
    console.log(event.target.value);  
  }

  return <input type="text" onChange={handleInputChange} />;
}

    

In the code above, event is a synthetic event. It mimics a typical event. It works uniformly despite the choice of browser. React uses Synthetic Events to keep event handling consistent across different browsers.

3. Passing Arguments to Event Handlers

On occasion, you want to include extra arguments to your event handler, besides the event object. Two common methods are available to do this:

a. Employing an arrow function

You can use an arrow function. With this method, you can pass additional arguments.


function App() {
  function handleClick(message) {
    alert(message);
  }

  return <button onClick={() => handleClick('Hello!')}>Click Me</button>;
}

    

In this example, the arrow function () => handleClick('Hello!') lets you give 'Hello!' as an argument to handleClick.

b. Leveraging bind()

An alternative is using the method .bind(). It helps to pass arguments.


function App() {
  function handleClick(message) {
    alert(message);
  }

  return <button onClick={handleClick.bind(this, 'Hello!')}>Click Me</button>;
}

    

Here, using .bind(this, 'Hello!') results in a new function creation. There is always a passing of 'Hello!' as the initial argument.

Key Takeaways

  • In React, camelCase is favored for Event Handler names. For instance, we use "onClick" instead of "onclick".
  • React also uses Synthetic Events. These events extend React's events. They ensure consistency across browsers.
  • Arguments can be passed to event handlers. Methods for this include arrow functions. Another method is .bind().