Copy text to the Clipboard in React without a package

Today we’ll show you how to copy text to the clipboard in React without a package. In the previous article we show you how to Copy text to the Clipboard in ReactJS using NPM Package.

Let’s take an example where we will render the textbox and button component to perform the demo.

Steps: Copy text to the clipboard

  1. Create react app
  2. Design a page
  3. Implement logic for copy text to the clipboard
  4. Output

1. Create react app

First, we will have a simple react application. For that use the following command to set up the startup react application.

2. Design a page

To design a page, we will use the textarea for entering the text and button for copy to clipboard.

App.js

3. Implement logic for copy text to the clipboard

Let’s do a couple of changes in the App component to implement the logic. Use the ref attribute for textarea to invoke the select method. Manage the state variable for button click to show the text has been copied. At last write a logic for copy text to clipboard on click event of the button.

App.js

Here we have used the Logical AND Operator to display the button.

4. Output

Output - Copy text to the Clipboard in React without a package - Clue Mediator
Output – Copy text to the Clipboard in React without a package – Clue Mediator

That’s it for today.
Thank you for reading. Happy Coding..!!

Demo & Source Code

Github Repository StackBlitz Project
If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

4 Responses

  1. Shanmukha says:

    document.refs is deprecated. What alternatives can be used here?

Leave a Reply

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