How to create a context menu in React
React is a free, open-source JavaScript framework used to create user interfaces. It can be used to create mobile, web, and desktop applications.
When you right-click on your screen, a menu, known as the context menu, appears. Below is a guide to creating a context menu.
Set up Bootstrap in React
Bootstrap is a free and open-source CSS framework used by front-end developers to build user interface components for mobile and web development. Here bootstrap is utilized by adding the "container" class. This class is a part of bootstrap's grid system and is used to create a container with a responsive fixed width. It helps in centering and aligning the content within the container.
You can easily install it in React using the following command.
npm i bootstrap
Build context menu
Create a components directory and add a new JavaScript file named ContextMenu.js, where you will write the code for your context menu.
import React from "react";
//define a functional component for the right-click context menu
function RightContext() {
//state variables
const [context, setContext] = React.useState(false);
const [xyPosition, setxyPosition] = React.useState({ x: 0, y: 0 });
//event handler for showing the context menu
const showNav = (event) => {
event.preventDefault();
setContext(false);
const positionChange = {
x: event.pageX,
y: event.pageY,
};
setxyPosition(positionChange);
setContext(true);
};
//event handler for hiding the context menu
const hideContext = (event) => {
setContext(false);
};
//function to set the chosen menu option
const [chosen, setChosen] = React.useState();
const initMenu = (chosen) => {
setChosen(chosen);
};
//JavaScript XML (JSX) returned by the component
return (
<>
<h2 className="mb-3">Context Menu Example</h2>
<h3> Right Click anywhere to preview the context menu </h3>
<div
className="contextContainer"
onContextMenu={showNav}
onClick={hideContext}
>
{chosen && <h4>"{chosen}" is chosen</h4>}
{context && (
<div
style={{ top: xyPosition.y, left: xyPosition.x }}
className="rightClick"
>
<div className="menuElement" onClick={() => initMenu("Open with")}>
Open With
</div>
<div className="menuElement" onClick={() => initMenu("Copy")}>
Copy
</div>
<div className="menuElement" onClick={() => initMenu("Cut")}>
Cut
</div>
<div className="menuElement" onClick={() => initMenu("Paste")}>
Paste
</div>
</div>
)}
</div>
</>
);
}
export default RightContext;Code Explanation
Line 1: This line imports the React library.
Line 4:
RightContextis a component that represents the context menuLine 4–65: Inside the
RightContextfunction, three state variables are declared using theReact.useStatehook. These variables are:Line 6:
contextrepresents the visibility of the context menu, which is initially set tofalse.Line 7:
xyPosistionstores the x and y coordinates of the right-click event when it takes place, and it is initially set to{ x: 0, y: 0 }.Line 27:
chosenstores the text of the chosen menu option, and it is initially undefined.
Line 10–19: The
showNavfunction is an triggered when the context menu is about to be shown. It updates the state variables as follows:event handler In React event handlers determine which action is to be taken. Line 11: It calls
event.preventDefault()to prevent the default browser context menu from showing.Line 12: It sets
contexttofalseto hide the context menu if it is already visible.Line 13–15: It creates an
positionChangeobject with the x and y coordinates of the right-click event.Line 17: It sets the
XYPosistionvalues with thepositionChangeobject.Line 18: It sets
contexttotrueto show the context menu.
Line 22–24: The
hideContextfunction is an event handler triggered when a click event occurs outside the context menu. It setscontexttofalse, which hides the context menu.Line 28–30: The
initMenufunction is used to set the chosen menu option. It takes a parameterchosenand sets it as the new value of thechosenstate variable.
You can now import the RightContext component to your application in the app.js file and use the context menu for your application.
Free Resources