#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.ts3import { useEffect } from "react";45const useDisableRightClick = () => {6useEffect(() => {7const handleContextMenu = (event: MouseEvent) => {8event.preventDefault();9};1011document.addEventListener("contextmenu", handleContextMenu);1213return () => {14document.removeEventListener("contextmenu", handleContextMenu);15};16}, []);17};1819export 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.tsx3import React from "react";4import useDisableRightClick from "@/hooks/useDisableRightClick";56function DisableRightClick() {7useDisableRightClick();8return <></>;9}1011export default DisableRightClick;
Import the component globally on the root layout or import on certain pages.
©2024 Codeblockz
Privacy Policy