This website uses cookies to enhance the user experience

Handling Events

Share:

React.js creates a consistent event system across various browser types making it comfortable for event handling. All the DOM events wrapped inside synthetic events by React have similar behavior as the standard browser events. The synthetic events system in React assures that the properties of events are consistent across different browsers.

Handling events in React slightly differs from handling events on DOM elements. React events are named using camelCase, rather than lowercase. Also, with JSX, you pass a function as the event handler, rather than a string.

For example, let's say we were building a Star Trek movie application and needed to handle the event when Captain Kirk clicks on a button. We might have a simple button that logs a message when clicked:

<button onClick={greetCaptainKirk}>Greet Captain Kirk</button>

function greetCaptainKirk() {
  console.log('Hello, Captain Kirk!');
}

In the example above, the onClick attribute has a JavaScript function (greetCaptainKirk()) associated with it, unlike regular HTML where the attribute would have been a string.

Another difference is that in React, you cannot return false to prevent default behavior. You must call preventDefault.

Let's modify the example to show an alert instead of logging to the console. We would want to prevent the form from submitting and reloading the page:

function GreetingMessageForm() {
  function handleSubmit(event) {
    event.preventDefault();
    alert('Hello, Captain Kirk!');
  }

  return (
    <form onSubmit={handleSubmit}>
      <button type="submit">Greet Captain Kirk</button>
    </form>
  );
}

In the code snippet above, we used event.preventDefault() to stop the page from reloading when the form is submitted.

When using React, you generally don't need to call addEventListener to add listeners to a DOM element after it is created. Instead, provide a listener when the element is initially rendered.

The behavior of this keyword in JavaScript is a bit unusual compared to other languages. In JavaScript, this in a method points to the owner of the function. But in React, class methods are not bound by default. This implies that if you forget to bind this.greetCaptainKirk and pass it to onClick, this will be undefined when that function is actually called.

This is not React-specific behavior; it is a part of how functions work in JavaScript. Generally, if you refer to a method without () after it, such as onClick={this.greetCaptainKirk}, you are supposed to bind that method.

Let's extend our previous example by converting it to a class:

class GreetingMessageForm extends React.Component {
  constructor(props){
    super(props);
    this.greetCaptainKirk = this.greetCaptainKirk.bind(this);
  }
  
  greetCaptainKirk(event) {
    event.preventDefault();
    alert('Hello, Captain Kirk!');
  }

  render() {
    return (
      <form onSubmit={this.greetCaptainKirk}>
        <button type="submit">Greet Captain Kirk</button>
      </form>
    );
  }
}

Here in the constructor, we have bound the function to this so that it can access the correct context.

If binding this annoys you, you could use public class fields syntax to correctly bind callbacks:

class GreetingMessageForm extends React.Component {
  greetCaptainKirk = (event) => {
    event.preventDefault();
    alert('Hello, Captain Kirk!');
  };

  render() {
    return (
      <form onSubmit={this.greetCaptainKirk}>
        <button type="submit">Greet Captain Kirk</button>
      </form>
    );
  }
}

The above utilizes arrow functions that binds this to the enclosing lexical context.

In React, it is also possible to pass arguments to event handlers. Let's imagine we have a list of Star Trek characters, and we want to display specific greeting messages when the button associated with each of them is clicked. See the following example:

class CharacterGreeting extends React.Component {
  greetCharacter = (character, event) => {
    event.preventDefault();
    alert(`Hello, ${character}`);
  };

  render() {
    return (
      <div>
          { ['Kirk', 'Spock', 'McCoy'].map((character) => 
            <button key={character} onClick={(event) => this.greetCharacter(character, event)}>
              Greet {character}
            </button> 
          )}
      </div>
    );
  }
}

In this code snippet, a different callback is created each time the CharacterGreeting renders. Each callback uses an arrow function, so this is bound to the CharacterGreeting instance.

To sum up, event handling in React is achievable via Synthetic Events, which provide a consistent API across different browsers. Using functions as event handlers enables you to control the behavior more directly and explicitly, and strategies like binding this allow for significant flexibility in how events are handled.

0 Comment


Sign up or Log in to leave a comment


Recent job openings