React CopyToClipboard component

React CopyToClipboard component

Jan 16, 2021ยท

3 min read

Play this article

A quick post documenting a simple CopyToClipboard component I created this week. It allows users to create a git branch slug when working on a story.

blog-copy-to-clipboard-screenshot.png

Click the Clipboard Icon button and the user gets a git branch command copied to their clipboard, simply but very handy. For example it generates:

git checkout -b st-270-write-blog-post

Paste the command into the command line and we're off to the races ๐Ÿ˜€

It also shows a temporary message to the user to notify them that the copy was successful.

Usage

Supply the component with a getText function that returns the text you want to copy to the clipboard. In this case we're generating a git slug but it can be any string you like.

...
<CopyToClipboard getText={() => slugify(`${screenId}-${heading}`)} />
...

Component Code

This is a Functional React component using Typescript. We use the Clipboard API navigator.clipboard to access the system clipboard.

import React, { useState } from 'react';

import { IconClipboard } from '../Icons';

export type Props = {
  getText: () => string;
};
export const CopyToClipboard: React.FC<Props> = ({ getText }) => {
  const [copied, setCopied] = useState(false);

  const handleClick = () => {
    navigator.clipboard
      .writeText(getText())
      .then(() => {
        setCopied(true);
        setTimeout(() => {
          setCopied(false);
        }, 1000);
      })
      .catch(error => console.log('Handle the error better than this :-)'));
  };

  return (
    <>
      <button onClick={handleClick}>
        <IconClipboard />
      </button>
      {copied && <p>Copied!</p>}
    </>
  );
};

Check my previous post on how to get the clipboard icons for the button ๐Ÿ™‚

How to use Heroicons in your React app

ย