3
\$\begingroup\$

I have a React component with a copyToClipboard method, which all works fine, but feels extremely verbose and quite hacky (namely, having to create a new select element, hide it, focus/select/copy it and then delete it). From what I've read, there are a couple of different ways to achieve copy-to-clipboard functionality, but it seems as though this sort of approach is relatively common, and one or two of the other ways doesn't have great browser support yet.

This method gets called when a click event is triggered on a child component, which passes the value to be copied as a single argument.

Is there a nicer/better way to go about doing this?

copyToClipboard = (value: string) => {
  const copyTextarea = document.createElement('textarea');
  copyTextarea.value = value;
  copyTextarea.style.position = 'fixed';
  copyTextarea.style.opacity = '0';
  copyTextarea.style.pointerEvents = 'none';
  document.body.appendChild(copyTextarea);
  copyTextarea.focus();
  copyTextarea.setSelectionRange(0, value.length);

  try {
    document.execCommand('copy');

    this.showToastNotification(`Successfully copied ${value} to clipboard!`);
  } catch (err) {
    throw new Error(err);
  } finally {
    copyTextarea.remove();
  }
};
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.