2

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.

2 Answers 2

4

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>

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.