Important Update
The Guide Feature will be discontinued after December 15th, 2023. Until then, you can continue to access and refer to the existing guides.
Author avatar

Gaurav Singhal

How to Create a Right-click Menu in React

Gaurav Singhal

  • Jun 12, 2020
  • 8 Min read
  • 98,875 Views
  • Jun 12, 2020
  • 8 Min read
  • 98,875 Views
Web Development
Front End Web Development
Client-side Framework
React

Introduction

React is an excellent library for building component-based UI with reusability in mind. You can create tons of components and reuse them across multiple pages. Occasionally, for styling purposes, you may want to override the default right-click menu or the context menu in your React app.

You can easily create a context menu by creating a custom component for handling right clicks and displaying the menu. In this guide, you will learn how to create a reusable and flexible context menu component in your React app.

Implementation Overview

To override the default browser right-click menu, the first step is to prevent the default right-click behavior. This can be done by listening to the contextmenu event and using the preventDefault() method on the event.

1document.addEventListener("contextmenu", (event) => {
2  event.preventDefault();
3});
js

Next, capture the current (x,y) position, and render your component at that coordinate on the page. Get the x and y position from the pageX and pageY properties from the event object.

1document.addEventListener("contextmenu", (event) => {
2  event.preventDefault();
3  const xPos = event.pageX + "px";
4  const yPos = event.pageY + "px";
5  //
6});
js

Then, pass the coordinates as the position style attribute to the component. The critical point to note here is that the custom menu should have the position style set to absolute for the menu to open at the correct position.

1<ContextMenu style={{ top: xPos, left: yPos }} />
jsx

That's a general overview of implementation.

Creating a Custom ContextMenu Component

Start by defining the component and the state for the component.

1class ContextMenu extends Component {
2    state = {
3        xPos: "0px",
4        yPos: "0px:,
5        showMenu: false
6    }
7
8    render() {
9        // ...
10    }
11}
jsx

The state will contain the (x, y) position and a boolean state to show or hide the menu.

Next, add the event listeners in the componentDidMount lifecycle method in the component.

1class ContextMenu extends Component {
2    state = {
3        xPos: "0px",
4        yPos: "0px:,
5        showMenu: false
6    }
7
8    componentDidMount() {
9        document.addEventListener("click", this.handleClick);
10        document.addEventListener("contextmenu", this.handleContextMenu);
11    }
12
13    componentWillUnmount() {
14        document.removeEventListener("click", this.handleClick);
15        document.removeEventListener("contextmenu", this.handleContextMenu);
16    }
17
18    handleClick = (e) => {
19        // ...
20    }
21
22    handleContextMenu = (e) => {
23        e.preventDefault();
24
25        // ...
26    }
27
28    render() {
29        // ...
30    }
31}
jsx

Add two event listeners for the click and context menu event in the componentDidMount method. Don't forget to remove the event listeners in the componentWillUnmount method to avoid memory leaks from your component.

In the handleClick method, you need to close the menu if it's currently open in the page.

1handleClick = (e) => {
2  if (this.state.showMenu) this.setState({ showMenu: false });
3};
jsx

In the handleContextMenu method, all you have to do is prevent the default event from triggering, set the current (x,y) position of the right-click in the state, and display the menu.

1handleContextMenu = (e) => {
2  e.preventDefault();
3
4  this.setState({
5    xPos: `${e.pageX}px`,
6    yPos: `${e.pageY}px`,
7    showMenu: true,
8  });
9};
jsx

In the render method, create a list with the menu items and display it when the showMenu state is set to true.

1class ContextMenu extends Component {
2  // ...
3  render() {
4    const { showMenu, xPos, yPos } = this.state;
5
6    if (showMenu)
7      return (
8        <ul
9          className="menu"
10          style={{
11            top: yPos,
12            left: xPos,
13          }}
14        >
15          <li>Login</li>
16          <li>Register</li>
17          <li>Open Profile</li>
18        </ul>
19      );
20    else return null;
21  }
22}
jsx

If you check out the results now, you should be able to see your custom menu when you right-click on the page. You got the desired results, but this component still needs some refactoring. The menu component is hardcoded here; it's best if it comes in as a prop. That way, you can show a different context menu on different pages. Also, add some fade animation to the menu when it opens up using the react-motion library.

1class ContextMenu extends Component {
2  // ...
3  render() {
4    const { showMenu, yPos, xPos } = this.state;
5    return (
6      <Motion
7        defaultStyle={{ opacity: 0 }}
8        style={{ opacity: !showMenu ? spring(0) : spring(1) }}
9      >
10        {(interpolatedStyle) => (
11          <>
12            {showMenu ? (
13              <div
14                className="menu-container"
15                style={{
16                  top: yPos,
17                  left: xPos,
18                  opacity: interpolatedStyle.opacity,
19                }}
20              >
21                {this.props.menu}
22              </div>
23            ) : (
24              <></>
25            )}
26          </>
27        )}
28      </Motion>
29    );
30  }
31}
jsx

And now you can use the ContextMenu component from your root or the entry component as shown below.

1const CustomMenu = () => (
2  <ul className="menu">
3    <li>Login</li>
4    <li>Register</li>
5    <li>Open Profile</li>
6  </ul>
7);
8
9const App = () => (
10  <div className="App">
11    {/* ... */}
12    <ContextMenu menu={() => <CustomMenu>}>
13  </div>
14)
jsx

Creating a Custom Context Menu Using Hooks

The previous section outlined how to create a component to render a custom context menu. But that was a class component; you could do the same with functional components using hooks.

All state variables can be created and managed with the useState hook. Handle the callbacks using the useCallback hook and pass a dependency array to it so that it can memoize the results and only change when the dependencies get updated. Wrap all the logic in a separate custom hook and return the xPos, yPos and showMenu state variables from the hook.

1const useContextMenu = () => {
2  const [xPos, setXPos] = useState("0px");
3  const [yPos, setYPos] = useState("0px");
4  const [showMenu, setShowMenu] = useState(false);
5
6  const handleContextMenu = useCallback(
7    (e) => {
8      e.preventDefault();
9
10      setXPos(`${e.pageX}px`);
11      setYPos(`${e.pageY}px`);
12      setShowMenu(true);
13    },
14    [setXPos, setYPos]
15  );
16
17  const handleClick = useCallback(() => {
18    showMenu && setShowMenu(false);
19  }, [showMenu]);
20
21  useEffect(() => {
22    document.addEventListener("click", handleClick);
23    document.addEventListener("contextmenu", handleContextMenu);
24    return () => {
25      document.addEventListener("click", handleClick);
26      document.removeEventListener("contextmenu", handleContextMenu);
27    };
28  });
29
30  return { xPos, yPos, showMenu };
31};
jsx
1const ContextMenu = ({ menu }) => {
2  const { xPos, yPos, showMenu } = useContextMenu();
3  return (
4    <Motion
5      defaultStyle={{ opacity: 0 }}
6      style={{ opacity: !showMenu ? spring(0) : spring(1) }}
7    >
8      {(interpolatedStyle) => (
9        <>
10          {showMenu ? (
11            <div
12              className="menu-container"
13              style={{
14                top: yPos,
15                left: xPos,
16                opacity: interpolatedStyle.opacity,
17              }}
18            >
19              {menu}
20            </div>
21          ) : (
22            <></>
23          )}
24        </>
25      )}
26    </Motion>
27  );
28};
jsx

Conclusion

Consider this guide as a gateway to exploring more advanced use cases, such as creating custom hooks in functional components, overriding default browser UI components like context menu, etc. You will get better at developing custom UI components if you understand the implementation logic behind them. In any case, to override default behavior, the first thing you need to do is prevent the event by using preventDefault().