Sometimes, we want to copy text to clipboard programmatically in React.
In this article, we’ll look at how to copy text to clipboard programmatically in React.
Copy Text to Clipboard Programmatically in React
To copy text to clipboard programmatically in React, we can use the navigator.clipboard.writeText
method.
For instance, we write:
import React from "react";
export default function App() {
return (
<button
onClick={() =>
navigator.clipboard.writeText("Copy this text to clipboard")
}
>
Copy
</button>
);
}
We call navigator.clipboard.writeText
with the text string that we want to copy to the clipboard.
Now when we click Copy, we should see the text that we copied when we paste it.
Conclusion
To copy text to clipboard programmatically in React, we can use the navigator.clipboard.writeText
method.