11 Event Handling - biswajitsundara/react GitHub Wiki

The user interacts with the react app through the events

  • Event handlers determine what action is to be taken whenever an event is fired.
  • This could be a button click or a change in a text input.
  • React supports all events like click, change, mouseover etc that we have in HTML.
  • Similar to HTML DOM events, React can perform actions based on user events.

Rules

  • React events are written in camelCase - onClick instead of onclick
  • React event handlers are written inside curly braces - onClick={shoot} instead of onClick="shoot()"
  • Make sure not to include the round brackets () as that will invoke the function at the begining itself.

1. Basic Example

const BasicEvent = () => {
    
  const greetHandler = () => {
    alert("Hello User");
  };

  const meetHandler = (event, name) => {
    console.log(event);
    alert(`Good to meet you ${name}`);
  };

  return (
    <div>
      <button onClick={greetHandler}>Greet</button>
      <button onClick={(event) => meetHandler(event, "Biswajit")}>Meet</button>
    </div>
  );
};

export default BasicEvent;

2. Parameterized Event

Lets say when we click on a button, we pass some value and then execute the event.

  • We can't do this way <button onClick={hello('Alia')}> as this will invoke the function at the rendering time
  • We need to wrap within another function <button onClick= { () => {function(parameter)} }
  • If we are writing in one line we can get rid of one set of curly braces <button onClick= { () => function(parameter) }
const Parameterized = () => {
    
  const clickHandler = (userName) => {
    console.log(`Hello ${userName}`);
  };

  return (
    <div>
      <h1>Home</h1>
      <button
        onClick={() => {
          clickHandler("Alia");
        }}
      >
        Hello
      </button>
      <button onClick={() => clickHandler("Katrina")}>Another Hello</button>
    </div>
  );
};

export default Parameterized;

3. Accessing Event Object

When we work with events, we would need to work with the event object also

  • The event object is passed to the event handler that has triggered the event.
  • The name can be anything e, event etc and the sequence also doesn't matter.
const EventObject = () => {
    
  const clickHandler = (userName, event) => {
    console.log(`Hello ${userName}`);
    console.log(event.target);
    console.log(event);
  };

  return (
    <div>
      <h1>Home</h1>
      <button onClick={(event) => clickHandler("Katrina", event)}>Hello</button>
    </div>
  );
};

export default EventObject;
⚠️ **GitHub.com Fallback** ⚠️