Create a context menu in React js

Manish Mandal
How To React
Published in
3 min readDec 5, 2020

Sometimes we need to customize the right click for triggering some events in our application. The context menu can be useful for sites like a video blog, coupon listing for adding right-click options to play video, copy coupons, share on social media, etc. So in this tutorial, I’ll show you how to add a context menu to your React application. Let us get started

We will build a simple coupon which on right-click will show a context menu.

Requirements

  1. Create and open your React js project.
yarn create react-app yourprojectnamecd yourprojectname

2. Create a component directory and inside that directory create two files coupon.js and coupon.css

3. Now we will create the coupon design. Open your coupon.js file and paste the below code.

4. Now open the coupon.css file and paste the below CSS and import that file to our coupon.js file.

Now import your coupon component to the app.js file.

Refresh the browser and check the result

Ok, so we have created the design for our coupon now it’s time to add a context menu to the coupon.

5. Install react-contextmenu and react-icons to the project.

npm install react-contextmenu react-icons --saveor yarn add react-contextmenu react-icons

6. Import ContextMenu, MenuItem, and ContextMenuTrigger from the react-contextmenu module and icons from the react-icons module.

import { ContextMenu, MenuItem, ContextMenuTrigger } from "react-contextmenu";
import {FaRegCopy, FaList,FaEllipsisV, FaShareAlt} from 'react-icons/fa'
import {RiSendPlaneFill, RiDeleteBin6Line} from 'react-icons/ri'

7. Now we will wrap our HTML in the ContextMenuTrigger tag and also create some menu items using ContextMenu. Paste the below code in the coupon.js file.

Note:

  • The id in ContextMenuTrigger and ContextMenu should be the same.
  • React Icons are optional.
  • data attribute contains the coupon code which is then passed to copyCoupon method
  • The onClick method inside MenuItem will pass the data of data attribute to the copyCoupon method which will then use JavaScript navigator.clipboard method to copy the code to the clipboard.

8. Now it’s time to add styling to our contextMenu. Paste the below code inside your coupon.css file and refresh the browser to see the changes.

For any query, you can get in touch with me via LinkedIn

Hope you will like the tutorial below I have share live code and GitHub repository for reference.

--

--

Manish Mandal
How To React

Full Stack Developer | React JS | Next JS | Node JS | Vue JS | Wordpress. Connect with me https://www.linkedin.com/in/manishmandal21/