How to setup a copy to clipboard functionality in either react.js or next.js site
Hello, in this post I am going to show you how to code a copy to clipboard functionality in a next.js or react.js application in 2 simple steps
Step 1
Create a function with keyword copyText that accepts a parameter called entryText as shown below
function copyText(entryText){
navigator.clipboard.writeText(entryText);
}
This function accepts data we want to save to clipboard in the parameter entryText, and the "navigator.clipboard.writeText(entryText)" saves it to clipboard when the function is invoked
Step 2
Within your jsx create a button and add an onlclick attribute that invokes the function we created above
<button onClick={() => copyText("hello there")}>Click me</button>
And thats it, whenever the button you created is clicked, the onclick attribute sends data (in this case we are sending a string of words, "hello there") to the copyText function which in turn saves it inside your clipboard.
Conclusion
Within two simple steps we have been able to add a copy to clipboard functionality to a button in our next.js website. As always thanks for reading. If you followed this tutorial and it worked for you or if you ran into any errors, you can leave a comment down below.