Simple Reusable React Component: Copy to Clipboard

As developers, we often need to add small but impactful features to our projects, like allowing users to copy text to their clipboard. Whether it’s for sharing a membership ID, a URL, or other dynamic data, having a reusable tool saves time and keeps the codebase clean.

Today, I’m excited to share a small but mighty React component called CopyToClipboard. It’s sleek, simple, and customizable, making it a perfect addition to your projects.

CopytoClipboard

The Component
Here's what makes the CopyToClipboard component special:

Minimal UI: The component features a clickable icon that toggles between "copy" and "copied" states for visual feedback.
Reusable: Pass the text you want to copy as a prop, and it just works.
Customizable: Style it to fit seamlessly into any design system.

Here’s the code:
import React, { useState } from "react";
import { HiMiniClipboardDocument, HiMiniClipboardDocumentCheck } from "react-icons/hi2";

const CopyToClipboard = ({ textToCopy }) => {
  const [copied, setCopied] = useState(false);

  const copyToClipboard = () => {
    navigator.clipboard
      .writeText(textToCopy)
      .then(() => {
        setCopied(true);
        setTimeout(() => setCopied(false), 1000);
      })
      .catch((err) => console.error("Failed to copy text:", err));
  };

  return (
    <button
      onClick={copyToClipboard}
      className="p-2 rounded hover:bg-gray-100 transition"
    >
      {copied ? (
        <HiMiniClipboardDocumentCheck className="text-green-500" />
      ) : (
        <HiMiniClipboardDocument className="text-gray-500" />
      )}
    </button>
  );
};

export default CopyToClipboard;

 

How It Works

Icon Feedback: The component uses React Icons for visual feedback. When the text is copied, the icon changes to indicate success for a brief moment.
Clipboard API: It leverages the native navigator.clipboard.writeText API, which works seamlessly in modern browsers.
Stateful UX: A simple useState hook toggles the "copied" state and resets it after one second.

How to Use
Here's how you can integrate the CopyToClipboard component into your project:

import CopyToClipboard from "./CopyToClipboard";

const App = () => {
  const membershipId = "12345678";

  return (
    <div>
      <h1>Your Membership ID</h1>
      <p>{membershipId}</p>
      <CopyToClipboard textToCopy={membershipId} />
    </div>
  );
};

export default App;
​


Why Use It?

The CopyToClipboard component saves you time while maintaining flexibility. Instead of rewriting logic every time you need this feature, simply drop the component into your project, pass the text as a prop, and you're done!

This small addition can make a big difference in user experience. I hope this component makes your React development a little sweeter and your users a little happier. 

Feel free to customize it and make it your own! Let me know how you’re using CopyToClipboard in your projects.

Happy coding!