Prevent copy and paste custom hook in React Js

Last updated : 29 July 2022

You can use copy, cut, and paste event handlers to prevent copying, cutting, and pasting text. Register these event listeners in a useEffect hook and remove them on dismounting the component.

Prevent copy and paste on the input level

The input properties onCopy, onPaste, and onCut handle the same at the input level. The disadvantage is that you must apply these three properties to all the inputs you want to protect from copying and pasting. Here is the implementation.

import { ClipboardEvent } from "react"
const SignupForm = () =>{
  const preventCopyPaste = (e: ClipboardEvent<HTMLInputElement>) => {
    e.preventDefault()
    alert("Copying and pasting is not allowed!")
  }
  return(
    <div>
      <form>
        <div>
          <label>Email:  </label>
          <input type="email" 
		     placeholder="abc@learnbestcoding.com" 
		     onCopy={(e) => preventCopyPaste(e)}  
		     onPaste={(e) => preventCopyPaste(e)}  
		     onCut={(e) => preventCopyPaste(e)}
	      />
        </div>
        <div>
          <label>Confirm Email:  </label>
          <input type="email" 
		     onCopy={(e) => preventCopyPaste(e)}  
		     onPaste={(e) => preventCopyPaste(e)}  
		     onCut={(e) => preventCopyPaste(e)}
	      />
        </div>
        </form>
    </div>
  )
}
export default SignupForm

Note that I call the preventCopyPaste method on all three events. The e.preventDefault() is the method that prevents copying and pasting. This method is ok to protect a few inputs as our HTML becomes lengthy and unreadable.

Prevent copy and paste with a custom hook

We can use a custom hook to achieve the same result. In that way, the restrictions are applied to the whole component. Individual event handlers at every input level are not necessary.

Here is the hook that does the restrictions

import { useEffect } from "react";
type EventType = "paste" | "copy" | "cut"
interface RestrictCopyPasteProps {
    window: Window
    actions: [EventType?,EventType?,EventType?]
}
export const useRestrictCopyPaste = (props: RestrictCopyPasteProps) => {
    useEffect(() => {
        props.actions?.forEach((action) => {
            action && window.addEventListener(action, preventPaste);
        })
        return () => {
            props.actions.forEach((action) => {
                action && window.removeEventListener(action, preventPaste);
            })
        };
    }, [props.window, props.actions]);

    const preventPaste = (e: Event) => {
        alert("Copying and pasting is not allowed!")
        e.preventDefault()
    }
}

The usage is simple as importing the hook into the page we want to apply restrictions.

import { useRestrictCopyPaste } from "./useRestrictCopyPasre"
const SignupForm = () =>{
useRestrictCopyPaste({window, actions:["copy","cut","paste"]})
  return(
    <div>
      <form>
        <div>
          <label>Email:  </label>
          <input type="email" placeholder="abc@learnbestcoding.com" />
        </div>
        <div>
          <label>Confirm Email:  </label>
          <input type="email"/>
        </div>
        </form>
    </div>
  )
}
export default SignupForm
Prevent copy paste custom hook react
Figure 1: Prevent copy paste custom hook react
Lance
By: Lance
Lance is a software engineer with over 15 years of experience in full-stack software development.
Read more...

Leave a comment

No Comments