Handle the onPaste event in React (with examples)

avatar
Borislav Hadzhiev

Last updated: Apr 7, 2024
2 min

banner

# Handle the onPaste event in React (with examples)

To handle the onPaste event in React:

  1. Set the onPaste prop on an element or add an event listener on the window object.
  2. Provide an event handler function.
  3. Access the pasted value as event.clipboardData.getData('text').
App.js
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> ); }

handle paste event

The code for this article is available on GitHub

The code sample shows how to handle the paste event on an input field or the window object.

App.js
<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.

App.js
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.

# Handle the onPaste event on the window object

The second example shows how to listen for the paste event on the window object.

App.js
useEffect(() => { const handlePasteAnywhere = event => { console.log(event.clipboardData.getData('text')); }; window.addEventListener('paste', handlePasteAnywhere); return () => { window.removeEventListener('paste', handlePasteAnywhere); }; }, []);
The code for this article is available on GitHub

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.

The function we returned from the useEffect hook is called when the component unmounts.
App.js
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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.