First, let create a function to clipboard something with Vanilla JS:
const copyToClipboard = (content) => {
const el = document.createElement("textarea");
el.value = content;
el.setAttribute("readonly", "");
el.style.position = "absolute";
el.style.left = "-9999px";
document.body.appendChild(el);
el.select();
el.setSelectionRange(0, 99999);
document.execCommand("copy");
document.body.removeChild(el);
alert("Copied the text: " + content);
};
Then lets create our handleClick function like this:
const handleClick = () => {
let exampleData = {
name: "item",
index: 1,
amount: 20
};
exampleData = JSON.stringify(exampleData);
copyToClipboard(exampleData);
};
And lets make a button to copy clipboard and add our handleClick method as an onClick prop;
<button onClick={handleClick}>Copy the data</button>
So here you go :)
Check these links to understand better;
How can I copy text to clipboard with JavaScript?
How TO - Copy Text to Clipboard - W3School
JSON.stringify() - W3School