Icon
Get In Touch
#nextjs

Disabling Right-Click Context Menu

This guide provides instructions to disable the right-click context menu in a Next.js 14 application using TypeScript and the App Router.

Create a Custom Hook

First, create a custom hook to encapsulate the logic for disabling the right-click context menu.

1
"use client";
2
// hooks/useDisableRightClick.ts
3
import { useEffect } from "react";
4
5
const useDisableRightClick = () => {
6
useEffect(() => {
7
const handleContextMenu = (event: MouseEvent) => {
8
event.preventDefault();
9
};
10
11
document.addEventListener("contextmenu", handleContextMenu);
12
13
return () => {
14
document.removeEventListener("contextmenu", handleContextMenu);
15
};
16
}, []);
17
};
18
19
export default useDisableRightClick;

Create DisableRightClick Component

Create a component and import the custom hook to avoid server side errors by not importing directly into your main layout or pages.

1
"use client";
2
// components/DisableRightClick/DisableRightClick.tsx
3
import React from "react";
4
import useDisableRightClick from "@/hooks/useDisableRightClick";
5
6
function DisableRightClick() {
7
useDisableRightClick();
8
return <></>;
9
}
10
11
export default DisableRightClick;

Import the component globally on the root layout or import on certain pages.

©2024 Codeblockz

Privacy Policy