Handle the onPaste event in React (with examples)

avatar

Borislav Hadzhiev

Tue May 03 20221 min read

banner

Photo by Joy

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 sample shows how to handle the paste event on an input field or on the window object.

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')); };

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); }; }, []);

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.

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.

Use the search field on my Home Page to filter through my more than 1,000 articles.