How to Create React Right Click Custom Context Menu

Last updated on: by Digamber

When you right-click on your screen, a menu appears on the screen. This menu is known as the context menu. It contains certain menu items that help you perform specific actions.

In this article, you will learn how to create a custom context menu in React JS using React useState hook in a function component without any trouble.

Building a custom right-click menu in React is easy. Our step-by-step guidance will also make it less complicated.

To create a right-click menu, you have to use the useState hook and event listener. The useState hook helps in tracking the state on component render. On the other hand, the event listener will give us access to x and y positions.

We will create some typical JavaScript functions. These functions will trigger when a user right-clicks on the screen to open the context menu.

Let us find out how to create a context menu with a custom function component. Also, to ideally show the context menu through the right clicks.

Build React Application

React offers a CRA tool, “CRA refers to create react app; This tool allows you to create new React app.”

Make sure to set up Node and Npm on your machine.

npx create-react-app react-context-app

After you ran the above command, a new blank project is created.

Now that you are ready to enter into the project’s root.

cd react-context-app

Set Up Bootstrap in React

Bootstrap helps front-end developers to build user interface components for web and mobile applicaiton development.

This handy library can be installed in React with just a single command using the npm.

npm i bootstrap

You have to inoculate bootstrap in React; Head towards the src/App.js file; here, you must import the bootstrap CSS path as mentioned below.

import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
function App() {
  return <div></div>;
}
export default App;

Make New Function Component

A function component opens the doorway to build desired functionalities with intuitiveness in React.

Creating a functional component is not rocket science; just create the components/ directory with the RightContext.js file.

Here is what a basic function looks like:

import React from 'react'
function Profile() {
  return (
    <div>RightContext page</div>
  )
}
export default RightContext

Build Context Menu in React

In our context menu, we will show four menu items. You can manifest the context menu by clicking on the coloured area on your screen.

Hence, we need to manage the state that you can do it by useState hook. And yes, we will require a couple of custom functions to capture and set the element’s position, x and y.

Update all the code within the components/RightContext.js function component file.

import React from "react";
function RightContext() {
  const [context, setContext] = React.useState(false);
  const [xYPosistion, setXyPosistion] = React.useState({ x: 0, y: 0 });
  const showNav = (event) => {
    event.preventDefault();
    setContext(false);
    const positionChange = {
      x: event.pageX,
      y: event.pageY,
    };
    setXyPosistion(positionChange);
    setContext(true);
  };
  const hideContext = (event) => {
    setContext(false);
  };
  const [chosen, setChosen] = React.useState();
  const initMenu = (chosen) => {
    setChosen(chosen);
  };
  return (
    <>
      <h2 className="mb-3">React Right Click Context Menu Example</h2>
      <div
        className="contextContainer"
        onContextMenu={showNav}
        onClick={hideContext}
      >
        {chosen && <h1>"{chosen}" is chosen</h1>}
        {context && (
          <div
            style={{ top: xYPosistion.y, left: xYPosistion.x }}
            className="rightClick"
          >
            <div className="menuElement" onClick={() => initMenu("Refactor")}>
              Refactor
            </div>
            <div className="menuElement" onClick={() => initMenu("Cut")}>
              Cut
            </div>
            <div className="menuElement" onClick={() => initMenu("Copy")}>
              Copy
            </div>
            <div className="menuElement" onClick={() => initMenu("Paste")}>
              Paste
            </div>
          </div>
        )}
      </div>
    </>
  );
}
export default RightContext;

Style Right Click Menu

After creating the context menu component, we need to write some custom CSS, which will make our right-click custom menu look better..

Open and update src/App.css with below code.

.contextContainer {
  z-index: 1;
  width: 100%;
  height: 500px;
  background: #673ab7;
}
.rightClick {
  z-index: 12;
  position: fixed;
  background: rgb(240, 200, 1);
}
.menuElement {
  color: #222222;
  cursor: pointer;
  padding: 17px 36px;
}
.menuElement:hover {
  color: #fff;
  background: #009688;
}

Update Global Component

You now need to get into the src/App.js, and here you have to add the given code.

import RightContext from "./components/RightContext";
import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
import "./App.css";
function App() {
  return (
    <div className="container">
      <RightContext />
    </div>
  );
}
export default App;

Test React Application

You will have to run the development server using the suggested command to view the feature we recently built.

npm start
http://localhost:3000

How to Create React Right Click Custom Context Menu

Conclusion

In this guide, we shed light on the process of building a custom context menu component in React. Not just that, we also learned how to add a custom context menu in React JS with a function component.

Digamber

I am Digamber, a full-stack developer and fitness aficionado. I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, ECMAScript, React, Angular, Vue, Laravel.