React Events

Updated:

Event handling is a necessary process for any interactive application, and in React it involves dealing with props and functions.

Here is an example of a button that, when clicked, logs "clicked" in the console.

function Btn() {
  const handleClick = () => console.log("clicked");

  return <button onClick={handleClick}>Submit</button>;
}

Each time the button is clicked, React invokes the handleClick function and logs "clicked" in the console.

Note that if you want to add a click handler to a button, give onClick a reference to the click handler, not a function invocation onClick={handleClick()}. This will allow React to invoke the function when the event occurs rather than when the component is rendered.

It is also a good practice to encapsulate the event handler in its own function and name it handle followed by the event name.

Whenever you have an event handler in React, try to keep it within the component that handles the event. This pattern will make it easier to access the state and props of the component using the JavaScript scoping rules.

function Btn({ message }) {
  const handleClick = () => console.log(message);

  return <button onClick={handleClick}>Submit</button>;
}

Even though React will have to recreate the event handler function each time it is rendered, it is very unlikely to cause a performance issue, since the cost of creating and destroying functions in JavaScript is negligible.

Finally, whenever an event handler is called by React, it will pass an object as the first argument to the event handler, which contains all the information about the event that was triggered.

Although there is a lot of data in the event object, one of the most used properties is the target property, which represents the element that triggered the event.

function TextInput() {
  const handleChange = (event) => {
    const text = event.target.value;
    console.log(text);
  };

  return <input placeholder="Type some text" onChange={handleChange} />;
}

In the example above, the handleChange function is called each time the user types in the input field. The event object is passed to the handleChange function and the target property is used to access the value typed by the user in the input field.