Copy to clipboard in React

Yashod Perera
2 min readNov 3, 2020

--

Photo by Bethany Cirlincione on Unsplash

Copy the file path to clipboard is quite useful in many applications. There are several ways of doing that.

  1. Using DOM element
  2. Using Ref
  3. Using navigator
  4. Using a fake DOM element

Using DOM element.

This is common for any JS framework and primitive way of doing this. It can be obtained as follows.

// Html elements.
<input type="text" value="Value to be copied" id="clipBoard">
<button onClick={() => this.copyToClip()}>Copy to clipboard</button>
// Function.
copyToClip = () => {
// select the element.
var clipBoard = document.getElementById("clipBoard");

// select the element.
clipBoard.select();
// copy the value of the element.
document.execCommand("copy");
};

Using Ref

Ref is a very popular method in react to get a reference other than calling document.getElemenetById . Let’s figure out how to use Ref for copy to clipboard.

// Html elements.
<input ref={(clipBoard) => this.clipBoard = clipBoard}
value='Value to be copied' />
// Function.copyToClip = () => {
// Select the DOM element using ref.
this.clipBoard.select();
// copy the value of the element.
document.execCommand('copy');
};

Using Navigator

This is an easy way of doing this. But there are some issues with this method. Which some of the browsers are not support this.

navigator.clipboard.writeText('stuff to write');

This can be used as a callback as well to indicate whether the value is copied to the clipboard.

navigator.clipboard.writeText('stuff to write')
.then(
success => {},
failed => {},
)

Using a Fake DOM

Fake DOM is made to use execCommand and then remove the created DOM element.

copyToClip = (clipValue) => {
// Create a fake element.
const fakeElement = document.createElement('input');
// Set the value to the fake element.
fakeElement.value = clipValue;
document.body.appendChild(fakeElement);

// Select the element.
fakeElement.select();
// Copy the value and remove the element.
document.execCommand('copy');
document.body.removeChild(fakeElement);
};

Hopefully this is helpful.

If you have found this helpful please hit that 👏 and share it on social media :).

--

--

Yashod Perera
Yashod Perera

Written by Yashod Perera

Technical Writer | Tech Enthusiast | Open source contributor

No responses yet