React Events

React Events

A Beginner's Guide to Exploring React Events

·

4 min read

One of the key features of React is its event handling system, which enables the user to interact with a webpage through specific events such as click or hover. In this blog, we’ll explore React Events in detail and also highlight the differences between HTML and React event handling systems.

What are React Events?

I hope you already know how to handle events in HTML and JavaScript. If not, do check out my article. Handling events with React is very similar to handling events in DOM elements, with a few differences.

Just like HTML DOM events, React can perform actions based on user events. React supports a wide range of events, including mouse events, keyboard events, touch events, and form events. Check out the full list.

Note: Events are the actions to which javascript can respond.

The react event handling system is known as Synthetic Events. React Synthetic Event acts as a wrapper around the native browser event object. It ensures consistency by normalizing events across different browsers and platforms so that they have the same properties.

Event handling in React is more efficient and consistent using the Synthetic Event system.

How to use events in React?

To handle an event in React, you need to attach an event listener to the element that you want to listen for events on. Let's check out an example of how to handle a click event in React using a functional component. We will use the onClick event handler for this purpose:

import React from 'react';

function App() {
    function handleClick() {
      alert('Button clicked..!!');
   }
  return (
      <div>
          <button onClick={handleClick}>Click me</button>
      </div>
  );
}

export default App;

In this example, we define a function called handleClick that displays an alert when the button is clicked. We then attach the handleClick function to the onClick event of the button element using JSX syntax.

Differences Between Html And React Event Handling

🔈Handling events

Handling events with react have some syntactic differences from handling events on DOM. These are:

  • React events are written in camelCase syntax instead of lowercase.

    onClick instead of onclick.

  • In React, we pass a function as an event handler instead of passing a string React event handlers are written inside curly braces:

    onClick={clickHandler} instead of onClick="clickHandler()".

Event declaration in plain HTML:

<button onclick="clickHandler()">
  Clicked
</button>

Event declaration in React:

<button onClick={clickHandler}>
  Clicked
</button>

🔈Use preventDefault

In React, we need to use preventDefault to explicitly prevent the default behavior of an event, as opposed to simply returning false like in HTML.

In plain HTML, to prevent the default form submission behavior, we can write:

<form>
  <button onclick="console.log('Form submitted!'); return false">
    Submit
  </button>
</form>

In React, we can write it as:

function Form() {  
 function handleClick(e) {  
        e.preventDefault();  
        console.log('Form submitted!');
    }  
    return (  
       <form>
        <button onClick={handleClick}>Submit</button>
       </form>
    );  
}

In the above example, e(event), is a Synthetic Event. You can take a look at this to know more about Synthetic Events.

🔈Function Calling

When using HTML, we call a function by adding "()" to the function name. Alternatively, we can use the addEventListener method to assign events and listeners. In React, however, we should use the method name without the "()" added to it.

HTML Example:

 <button onclick='handleClick()'>

React Example:

<button onClick={handleClick}>

Passing Data to Event Handler

In React functional components, we can pass data to an event handler using arrow functions to wrap the handler function and pass the data as an argument:

import React from 'react';

function App() {
function handleClick(data) {
  alert(`Message received: ${data}`);
}
  return (
    <button onClick={() => handleClick('Hello World!')}>
      Click me
    </button>
  );
}

export default App;

In this example, when you click the button, the handleClick function is called with the data "Hello World!" as an argument, and it displays the data, along with the message in the alert box:

Conclusion

React Events play an important part in building dynamic and interactive web applications with React. With the ability to pass data and handle events, React events are an essential part of building modern web applications. Event handlers determine what action should be taken when an event occurs.

And with this, we have come to an end in this React Basic Series, I hope this series will help get you started with React and that you have a great time in building your own applications.


References


Thank you for taking the time to read this blog. Hope you found it informative and enjoyable!

Do let me know your thoughts and feel free to connect with me on Twitter.

Catch you guys on the next one. Cheers .. ✌️

Did you find this article valuable?

Support Raj Sarkar by becoming a sponsor. Any amount is appreciated!