Onjsdev

Share


React Right Click

How To Handle Right Click In React


By onjsdev

Feb 7th, 2024

When a user right clicks in a browser, a default box(context menu) appears with some actions such as copy and paste. However, in react applications, we can prevent the default behavior and create a custom context menu on right click.

In this article, we will discuss how to handle right-click in React using the onContextMenu event.

What is the onContextMenu Event?

The onContextMenu event is fired when the user right-clicks on an element or presses the context menu key on their keyboard. It is a built-in event in React that we can use to handle the right-click event.

How to Use the onContextMenu Event?

To handle the right-click event, you need to attach the onContextMenu event to the element that you want to listen for the right-click event. You can then define a callback function to handle the right-click event and pass it as a prop to the element.

Let's look at an example:

import React from 'react';

function MyComponent() {
  const handleContextMenu = (event) => {
    event.preventDefault(); // prevent default context menu from showing up
    console.log('Right-clicked!');
  };

  return (
    <div onContextMenu={handleContextMenu}>
      Right-click me!
    </div>
  );
}

In this example, we've created a function called handleContextMenu that logs a message to the console when the user right-clicks on the div element. We've then added the onContextMenu event to the div and passed in the handleContextMenu function as the event handler.

The event.preventDefault() method is used to prevent the default context menu from showing up when the user right-clicks on the element.

How To Pass Data To Event

You can also pass data from the component to the handleContextMenu callback function.

Here is the example, but this time using an arrow function as a callback.

import React from 'react';

function MyComponent() {
  const handleContextMenu = (event, data) => {
    event.preventDefault(); // prevent default context menu from showing up
    console.log('Right-clicked!', data);
  };

  return (
    <div onContextMenu={(e) => handleContextMenu(e, 'some data')}>
      Right-click me!
    </div>
  );
}

In addition to logging a message or passing data, you can also perform other actions when the user right-clicks on an element. For example, you could open a custom context menu, show a tooltip or display a modal window.

Conclusion

In conclusion, modifying the default right-click behavior in React using the onContextMenu event is a simple.

By attaching the onContextMenu event to an element and defining a function to handle the event, you can perform a variety of actions on right click in React.

Thank you for reading.