How to handle the onPaste event in React with examples

Handle the onPaste event in React (with examples)

You will learn how to handle the onPaste event in React with examples. Some ways will be covered, for example, using the onPaste event attribute or assigning onPaste with a function method.

Handle the onPaste event in React with examples

The onpaste attribute is fired when the user pastes something into the tag. Although the onpaste attribute is supported in all HTML tags, it is not always possible to paste the content into a tag, for example, a <p> tag, unless that tag has the contenteditable attribute set to “true.”


<element onpaste="script">

There are 3 ways to paste the content into a tag:

  • Press CTRL + DRAW
  • Select “Paste” from the “Edit” menu on the browser
  • Right-click and select the “Paste” command

Using the onPaste event attribute

This way, we will use the onPaste usage in the input tag or text fields like the commonly used events like onClick or Change. Editable elements will have this event built into them. You need to add the attribute, which will be received when the event is fired.


import React, { useState } from "react";

const App = () => {
  const [value, setValue] = useState("");
  const handlePaste = () => {
  return (
      <h2>Handle the onPaste event in React | LearnShareIT</h2>
      <hr />
      <form className="form">
          onChange={(e) => setValue(}
export default App;


When you paste a text into the input, the program can catch this event and run it through the handlePaste function so you can handle it easily. When users use the paste method, as I listed above, they are caught by the program.

Assigning onPaste with a function method

This way, we will assign a function to handle the onPaste event on the page. You can use this in a class component because React is a Javascript-based library. There’s little difference in event handling between ReactJS and Javascript. With Javascript, a function will be called to execute when an event occurs. But with React, a Component method is called when the event occurs.


onPaste: function() { console.log(this.value); },

As per the above replacement code, we have assigned an anonymous function to the onPaste event to handle this user event. The results returned to us are also the same. I wish you success with these methods.


To sum up, you have quickly learned two ways to handle the onPaste event in React with examples. However, it would help if you used the onPaste event attribute because it will be neater and easier to follow for the developer.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *