React Events

Similar to HTML DOM events, React allows handling user interactions through various events like click, change, and mouseover.



Adding Events in React

In React, event names use camelCase syntax, unlike standard HTML. Event handlers in React are written inside curly braces.

HTML:

<button onclick="triggerAction()">Click Me!</button>

React:

<button onClick={triggerAction}>Click Me!</button>




Defining Event Handlers

Here’s how to define an event handler within a component:

function ActionButton() {
  const triggerAction = () => {
    alert("Action Triggered!");
  };

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

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<ActionButton />);




Passing Arguments to Event Handlers

To pass arguments to an event handler, use an arrow function.

Passing the string “Success!” as an argument to the triggerAction function:

function ActionButton() {
  const triggerAction = (message) => {
    alert(message);
  };

  return (
    <button onClick={() => triggerAction("Success!")}>Click Me!</button>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<ActionButton />);




React Event Object

Event handlers also have access to the event object that triggered the action. This is useful for handling more complex events.

Using an arrow function to manually pass the event object:

function ActionButton() {
  const triggerAction = (message, event) => {
    alert(event.type);
    // 'event' represents the React event that triggered the function, in this case the 'click' event.
  };

  return (
    <button onClick={(event) => triggerAction("Success!", event)}>Click Me!</button>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<ActionButton />);
Scroll to Top