3

I have a section that has a table now I want the user to be able to copy the HTML code of the table to the clipboard.

Here is my solution on code sandbox : live demo

Js code below

import React, { useState, useRef } from "react";

export default function App() {
  const tableRef = useRef(null);
  const [copySuccess, setCopySuccess] = useState("");

  const copyToClipboard = (e) => {
    const code =tableRef.current.innerHTML;
    console.log('code', code);
    document.execCommand("copy");
    e.target.focus();
    setCopySuccess("Copied!");
  };

  return (
    <div className="App">
      <div ref={tableRef} className="table">
        <table>
          <thead>
            <tr>
              <th>#</th>
              <th>First Name</th>
              <th>Last Name</th>
              <th>Username</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>1</td>
              <td>Mark</td>
              <td>Otto</td>
              <td>@mdo</td>
            </tr>
          </tbody>
        </table>
      </div>

      {document.queryCommandSupported("copy") && (
        <div>
          <button onClick={copyToClipboard}>Copy</button>
          {copySuccess}
        </div>
      )}
    </div>
  );
}

Unfortunately, this is not copying the HTML code.

What do I need to change to be able to copy HTML to the clipboard.?

What is wrong here?

The Dead Man
  • 6,258
  • 28
  • 111
  • 193
  • You need to select the contents of the table. See this for a function to select a table's contents: https://stackoverflow.com/questions/2044616/select-a-complete-table-with-javascript-to-be-copied-to-clipboard (then pass it `tableRef.current`) – Peter Collingridge Apr 12 '21 at 16:21
  • @PeterCollingridge check my live demo solution click copy u will see the console code return the table using tableRef.current.innerHTML; the problem is how do I copy that to clip board – The Dead Man Apr 12 '21 at 16:24
  • You can't use `document.execCommand("copy")` unless you select the content first. To write from a variable you will have to use `navigator.clipboard.writeText`. For details, see: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Interact_with_the_clipboard – Peter Collingridge Apr 12 '21 at 16:29
  • Do you want to copy the HTML text to the clipboard so that the user is going to paste the HTML "code" or do you want to copy the HTML elements so the user is going to paste the HTML table into let's say Word or some other application? – Krisztián Balla Apr 12 '21 at 16:30
  • @KrisztiánBalla I want to copy the HTML code by which user can paste eg into email as signature – The Dead Man Apr 12 '21 at 16:31
  • @PeterCollingridge i get this error with that https://i.stack.imgur.com/ttecA.png ? – The Dead Man Apr 12 '21 at 16:41
  • It's difficult to tell what that means. It could be an issue with the sandbox itself. Are you able to set up a simple react-app locally and test? I added `navigator.clipboard.writeText('...')` into a random react app I had running and it seemed to work. – Peter Collingridge Apr 12 '21 at 19:59

1 Answers1

1

The problem is it copies selected/highlighted text to the clipboard so you just need to do that programmatically before running execCommand.

  1. Add a hidden input (set invisible and position absolute/off-screen)
  2. In copy function, set the value of that input to the html
  3. select the hidden input with the select event
  4. execCommand(‘copy’);

EDIT

It might work with an input type of hidden or setting display: none; but I vaguely remember this blocking the select event when I did this a few years back.

Luke Weaver
  • 271
  • 1
  • 9
  • please here is link to code sandbox can you show your solution via code ? https://codesandbox.io/s/copy-html-to-clipboard-ouyri?file=/src/App.js u can just edit that code – The Dead Man Apr 12 '21 at 16:30
  • @TheDeadMan I saved changes to your codesandbox project and added comments to help clarify the details – Luke Weaver Apr 12 '21 at 18:09
  • when u save the project it become forked so you need to share the new saved project so that I can see your canges thanks – The Dead Man Apr 12 '21 at 19:05
  • @TheDeadMan Sorry about that! https://codesandbox.io/s/copy-html-to-clipboard-forked-4tmsh?file=/src/App.js – Luke Weaver Apr 12 '21 at 19:36