'Copy to clipboard using ReactJS

I am calling an API to fetch the data of an object. The object properties are as follows:

obj:{
   name: "item", 
   index:1,
   amount :20,
}

What I want is to simply copy the properties of this object (name, index, amount) to clipboard. How can I achieve this in React and javascript? Thanks in advance.



Solution 1:[1]

You can use Clipboard API and writeText function.

writeText accepts a string to write to clipboard. Here I use JSON.stringify to convert props object to string.

function App() {
  return (
    <div>
      <p>Click button below and check contents of your clipboard</p>
      <ClipboardButton index={1} name="item" amount={20} />
    </div>
  );
}

function ClipboardButton(props) {
  function handleClick() {
    navigator.clipboard.writeText(JSON.stringify(props));
  }

  return <button onClick={handleClick}>Copy to clipboard</button>;
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 macborowy
Solution 2