Create copy-to-clipboard button using react-js
Post by: Niraj Dhungana
Posted on: Nov 29 2021
This is the demo which we are going to create.
If you click on this button it will copy some text to your clipboard. OMG You just copied a virus, just kidding 😜 it's just some plain text. If you use
ctrl+v or paste using right click you will find out what text you just copied?
To copy text to clipboard we have an object called
window.navigator. This object contains the information about browsers. Most of the major browsers support it. You can read more about it here.
I assume here you already have a React app to implement copy to clipboard demo. If not then please create one.
Now I will create a component called
CopyToClipboard. You can also create one or use a pre-existing component like an
Here the code explains itself but let me explain if you feel any confusion. We have this component called
CopyToClipboard. Where we are accepting a prop called
textToCopy. Which we will use to copy to clipboard.
Then we are just rendering a
button inside a
div with some tailwind css classes. You can skip those class names if you don’t know or don’t want to use tailwind css.
onClick listener to the button and add a new method where we can listen and handle the actual logic to copy the text.
Here the new code is on line number 2 and line number 7.
Now inside our copyToClipboard method we can use this small logic. To copy text to the clipboard. Here I am just using comment but you can use the
prop which we accepted earlier.
The code above is ok if you just want to copy the text but let’s make it interesting. Let's see how we can display an alert or notify our user that they did something. Messages like copied or failed to copy.
For that I am going to change the text from inside the button and the style of the button. And if anything goes wrong I will just log it to the
Handling error and success
navigator.clipboard.writeText() returns a
promise. So, we can use the
.then() method to capture success and error both.
And don’t be confused here to capture both success and failed response. We can pass two methods inside the
Now here if the copy process is successful then I want to change the text inside that button for two second. Otherwise if anything goes wrong I want to log that to the
To achieve what I just told. I will add a new state inside our component called
copied. And change some of the styles and text of the
button if the state is
Ok this is how we can do it. Now let’s add the logic inside the
.then() method which will update our
copied state. According to the user's behaviour.
Now you have the exact thing that you saw in the demo at the beginning of this post.
Complete source code.