Last updated: Apr 7, 2024
Reading time·2 min
To handle the onPaste event in React:
onPaste
prop on an element or add an event listener on the window
object.event.clipboardData.getData('text')
.import {useEffect} from 'react'; export default function App() { const handlePaste = event => { console.log(event.clipboardData.getData('text')); }; useEffect(() => { const handlePasteAnywhere = event => { console.log(event.clipboardData.getData('text')); }; window.addEventListener('paste', handlePasteAnywhere); return () => { window.removeEventListener('paste', handlePasteAnywhere); }; }, []); return ( <div> <h2>Hello world</h2> {/* 👇️ Handle paste event on an input field */} <input onPaste={handlePaste} type="text" id="message" autoComplete="no" /> </div> ); }
The code sample shows how to handle the
paste
event on an input
field or the window
object.
<input onPaste={handlePaste} type="text" id="message" autoComplete="no" />
The paste
event is triggered when the user initiates a paste
action.
We can use the
getData()
method on the clipboardData
property of the event
object to access the data
the user pasted.
const handlePaste = event => { console.log(event.clipboardData.getData('text')); };
If you need to turn off autocomplete on an input field, check out the following article.
window
objectThe second example shows how to listen for the paste
event on the window
object.
useEffect(() => { const handlePasteAnywhere = event => { console.log(event.clipboardData.getData('text')); }; window.addEventListener('paste', handlePasteAnywhere); return () => { window.removeEventListener('paste', handlePasteAnywhere); }; }, []);
We passed an empty dependencies array to the
useEffect hook because we only
want to register the paste
event listener once - when the component mounts.
useEffect
hook is called when the component unmounts.return () => { window.removeEventListener('paste', handlePasteAnywhere); };
We used the removeEventListener() method to remove the event listener that we previously registered.
The cleanup step is important because we want to make sure we don't have any memory leaks in our application.
You can learn more about the related topics by checking out the following tutorials: