How to make a react copy to clipboard functional component


In this tutorial, we are going to explain how to make a react copy to clipboard functional component
This tutorial can be used in a React based app like Next.js
In short, to make a react function for copying clipboard:
- Use navigator.clipboard.writeText method provided by the browser to copy text to the system clipboard
- wrap this method inside a react function and pass in content as a parameter
The function will look like
const copyClipboard = (content)=> {navigator.clipboard.writeText(content)
console.log('copied content is', content)}
Whatever content has been passed as param will be copied to system clipboard, we add in also console log in case you would like to see what has been copied
Copy to clipboard function sample
Now, let's see for example in next.js how to make this kind of copy
Create App.js and copy the following code
import { useState } from "react";
export default function Test() {
const [content, setContent] = useState();
return (
<form className="flex flex-col w-1/3 p-2 gap-2">
<input className="border-2" placeholder="type in text to copy" onChange={(e) => setContent(e.target.value)}></input>
<button className="border-2 bg-black text-white rounded-xl"
onClick={()=>navigator.clipboard.writeText(content)}>Clik to copy </button>
</form>
);
}
So we have created a form with an input and a button, and whatever content the user has typed in input, it will be copied to clipboard
Test validation
Now when you run localhost:3000/test type in some text and click to copy
You can try out other colors like: aliceblue, aqua , azure ...
Conclusion
We have seen how to make a react function for copying content to clipbaord.
If you like the article, and want to add copy clipboard icon, you can check this article