惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

量子位
WordPress大学
WordPress大学
小众软件
小众软件
云风的 BLOG
云风的 BLOG
IT之家
IT之家
人人都是产品经理
人人都是产品经理
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Last Week in AI
Last Week in AI
博客园 - 【当耐特】
T
Tailwind CSS Blog
阮一峰的网络日志
阮一峰的网络日志
V
V2EX
宝玉的分享
宝玉的分享
博客园 - Franky
F
Fortinet All Blogs
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
GbyAI
GbyAI
Hugging Face - Blog
Hugging Face - Blog
Jina AI
Jina AI
D
Docker
博客园 - 聂微东
C
Check Point Blog
H
Help Net Security

任峻宏的小站

Debugging Memory Leaks in a Next.js Application Troubleshooting: Resolving Devise Issue in an API-only Application Using ActionCable and React to Create a Simple Chat App 纪念左耳朵耗子 - 任峻宏的小站 Using SSE to Implement ChatGPT in Rails Refresh Myself - 任峻宏的小站 战痘 - 任峻宏的小站 逆向的能量——生活需要批评者 - 任峻宏的小站 人活着必须要有目标 - 任峻宏的小站 《第一人称单数》读书笔记 - 任峻宏的小站 卸载英雄联盟 - 任峻宏的小站 我的 2021 年总结 - 任峻宏的小站 记我的爷爷 - 任峻宏的小站 Migrate from Webpacker to Vite 从入门到放弃 《人生算法》读书笔记 - 任峻宏的小站 《不拘一格》读书笔记 - 任峻宏的小站 我为什么很少写博客 - 任峻宏的小站 我的2020年总结 - 任峻宏的小站 如何避免冲动消费? - 任峻宏的小站 《不能不去爱的两件事》读书笔记 - 任峻宏的小站 记一次搬家 - 任峻宏的小站 My blog V3.0 has been published! 解决服务器上运行 bundle install 时 killed 的问题 解决生产环境不能发送邮件的问题 - 任峻宏的小站 解决内存泄漏记录 - 任峻宏的小站 勿忘初心 - 任峻宏的小站 关于 RSpec 的一点方法总结 - 任峻宏的小站 使用 AJAX 重载部分页面 - 任峻宏的小站 Nginx 添加 SSL 支持 - 任峻宏的小站 Nginx 中进行重定向配置 - 任峻宏的小站
How to Customize a Right-Click Menu in React
任峻宏 · 2023-08-16 · via 任峻宏的小站

When building web applications, sometimes you might need to provide a customized right-click context menu to enhance the user experience. In this article, I'm going to explore how to create a custom right-click menu in a React application.

Before starting, it's worth mentioning that there are some existing libraries available that offer solutions for context menu (like react-contextmenu or react-contexify or react-context-menu). If you don't want to use the library and want to roll up your sleeves to create a customized solution tailored to your application's unique needs, let's move on!

What is React Context Menu?

A context menu, often referred to as a right-click menu, is a pop-up menu that appears when a user right-clicks on an element. 

the oncontextmenu event is typically triggered by clicking the right mouse button. In the context of React, we can utilize the onContextMenu event to capture the right-click action. 

For further details, you can refer to the MDN Web Docs or w3schools Doc

Disable the Default Right-Click Menu

To prevent the default context menu from showing up, we can use the preventDefault() method on the event object:

function Home() {
 const handleContextMenu = (e) => {
   e.preventDefault(); // prevent the default behavior when right-clicked
   console.log("right click");
 };

 return (
   <div onContextMenu={handleContextMenu}>
     {/* Your content here */}
   </div>
 );
}

export default Home;

Creating a Customized Menu

First, let's create a new component called  CustomMenu. This component will render the menu items and handle the actions when a menu item is clicked.

This component takes two props: handleMenuItemClick for handling menu item clicks and menuPosition for positioning the menu based on the mouse coordinates.

import React from 'react';

function CustomMenu({ handleMenuItemClick, menuPosition }) {
 const menuItems = ['foo', 'bar', 'item3'];

 const handleClick = (item) => {
   handleMenuItemClick(item);
 };

 return (
   <div className="custom-menu rounded shadow bg-white absolute" style={{ left: menuPosition.x, top: menuPosition.y }}>
     {menuItems.map((item) => (
       <div className="cursor-pointer rounded px-4 py-2 hover:bg-slate-400" key={item} onClick={() => handleClick(item)}>
         {item}
       </div>
     ))}
   </div>
 );
}

export default CustomMenu;

Implementing the Custom Right-Click Menu

Now, let's integrate the custom context menu into our main component.

When the user right-clicks, we'll set the menuVisible state to true and also store the mouse coordinates to determine the menu position.

import React, { useState } from 'react';
import CustomMenu from './CustomMenu';

function Home() {
 const [menuVisible, setMenuVisible] = useState(false);
 const [menuPosition, setMenuPosition] = useState({ x: 0, y: 0 });

 const handleContextMenu = (e) => {
   e.preventDefault();
   setMenuVisible(true);
   // Store the mouse coordinates
   const mouseX = e.clientX;
   const mouseY = e.clientY;
   setMenuPosition({ x: mouseX, y: mouseY });
   
   // Add an event listener to handle clicks outside the menu
   document.addEventListener('click', handleOutsideClick);
 };
 
 const handleOutsideClick = (e) => {
   // Check if the click is outside the menu
   if (!e.target.closest('.custom-menu')) {
     setMenuVisible(false);
     document.removeEventListener('click', handleOutsideClick);
   }
 };

 const handleMenuItemClick = (item) => {
   switch (item) {
     case 'foo':
       // Perform the foo action
       break;
     case 'bar':
       // Perform the bar action
       break;
     default:
       break;
   }
   setMenuVisible(false);
 };

 return (
   <div onContextMenu={handleContextMenu}>
     {/* Your other content here */}
     {menuVisible && <CustomMenu handleMenuItemClick={handleMenuItemClick} menuPosition={menuPosition} />}
   </div>
 );
}

export default Home;

Now, let's take a look at the result:


Feel free to customize the design and behavior of the custom menu to fit your application's style and requirements.

With this approach, you can create context menus that provide specific actions and options, making your application more user-friendly and efficient.