React Right Click Custom Context Menu

A right-click custom context menu is a pop-up menu that appears when you right-click on a specific element or area in a software program or website. This menu is different from the default one that your operating system or browser provides, and it typically offers additional options and actions specific to the context you're in.

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

Table of Contents

  • Step 1: Build React Application
  • Step 2: Set Up Bootstrap in React
  • Step 3: Make New Function Component
  • Step 4: Build Context Menu in React
  • Step 5: Style Right Click Menu
  • Step 6: Update Global Component
  • Step 7: Test React Application

Step 1: 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

Step 2: 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 --legacy-peer-deps

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;

Step 3: 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

Step 4: 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;

Step 5: 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;
}

Step 6: 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;

Step 7: 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

Conclusion

In this guide, we shed light on the process of building a custom context menu component in React.

#react 

React Right Click Custom Context Menu
3.15 GEEK