React Events

React events is similar to handling events in plain JavaScript, but with some syntactical differences. React events are named using camelCase, rather than lowercase. With JSX, you pass a function as the event handler, rather than a string.

Basic Event Handling

We can handle events like clicks, form submissions, or keyboard inputs. Here’s a basic example of handling a click event:

import React from 'react';

function ClickButton() {
  const handleClick = () => {
    alert('Button clicked!');
  };

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

export default ClickButton;

Passing Arguments to Event Handlers

Sometimes, you may need to pass arguments to your event handlers. This can be done by wrapping your handler in an arrow function.

import React from 'react';

function ClickButton() {
  const handleClick = (message) => {
    alert(message);
  };

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

export default ClickButton;

Handling Form Events

Forms are a common use case for handling events in React. Here’s how you can handle a form submission and input changes:

import React, { useState } from 'react';

function LoginForm() {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log(`Username: ${username}, Password: ${password}`);
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label>
          Username:
          <input
            type="text"
            value={username}
            onChange={(e) => setUsername(e.target.value)}
          />
        </label>
      </div>
      <div>
        <label>
          Password:
          <input
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
          />
        </label>
      </div>
      <button type="submit">Login</button>
    </form>
  );
}

export default LoginForm;

Prevent Default Behavior: Use event.preventDefault() to prevent the default form submission behavior.

Controlled Components: Manage form inputs using React state and the onChange event.

Handling Synthetic Events

React implements a cross-browser wrapper around the browser’s native event system called SyntheticEvent. This wrapper ensures that events behave consistently across different browsers.

import React from 'react';

function SyntheticEvent() {
  const handleEvent = (event) => {
    console.log(event);
    console.log(event.nativeEvent);
  };

  return (
    <button onClick={handleEvent}>Click Me</button>
  );
}

export default SyntheticEvent;

Here ‘event’ is a synthetic event, a cross-browser object.

Unified Event System: Synthetic events provide a consistent API across different browsers.

Performance: Synthetic events are pooled and reused, improving performance.

Event Pooling

React pools events for performance reasons. This means that the event object is reused and its properties are nullified after the event callback has been invoked. If you need to access the event properties asynchronously, you should call event.persist().

import React from 'react';

function EventPooling() {
  const handleEvent = (event) => {
    event.persist();
    setTimeout(() => {
      console.log(event.type); // Accessing event properties asynchronously
    }, 1000);
  };

  return (
    <button onClick={handleEvent}>Click Me</button>
  );
}

export default EventPooling;