Detect right click in React-Code Examples

Victor Talmacinschi
Radu TM

Detect right click in React

JavaScript by Radu TM June 16, 2022

import React, { useState, useEffect } from "react";

const RightClickDetector = () => {
  // useState to track right clicks
  const [isRightClick, setIsRightClick] = useState(false);

  // useEffect to add/remove event listener
  useEffect(() => {
    // add event listener on mount
    document.addEventListener("contextmenu", handleRightClick);
    // remove event listener on unmount
    return () => document.removeEventListener("contextmenu", handleRightClick);
  }, []); // empty array ensures that effect is only run on mount and unmount

  const handleRightClick = (e) => {
    e.preventDefault();
    setIsRightClick(true);
  };

  return (
    <div>
      {isRightClick ? (
        <p>You right clicked!</p>
      ) : (
        <p>Try right clicking anywhere on this page.</p>
      )}
    </div>
  );
};

export default RightClickDetector;

0

22.541

Detect right click in React

JavaScript by Victor Talmacinschi June 16, 2022

import React, { useState } from "react";

const RightClickDetector = () => {
  // useState to track whether right-click has been detected
  const [isRightClick, setIsRightClick] = useState(false);

  const handleContextMenu = (e) => {
    // prevent default browser context menu from appearing
    e.preventDefault();
    // update state to reflect that a right-click has occurred
    setIsRightClick(true);
    // reset state after a short delay
    setTimeout(() => setIsRightClick(false), 250);
  };

  return (
    <div onContextMenu={handleContextMenu}>
      {isRightClick ? "Right Click!" : "Left Click!"}
    </div>
  );
};

export default RightClickDetector;

0

22.541

Related JavaScript Queries

Latest JavaScript Queries

Explore code examples by categories