Oliver Wolfson
ServicesProjectsContact

Development Services

SaaS apps · AI systems · MVP builds · Technical consulting

Services·Blog
© 2025 O. Wolf. All rights reserved.
Web Development
Copy to Clipboard for Text in JavaScript
In this article, we’ll cover how to copy text, images, and files to the clipboard with practical examples using React components, suitable for a Next.js app.
October 1, 2024•O. Wolfson

Copying content to the clipboard is a powerful way to improve the user experience in your app. Modern JavaScript and browser APIs make this easier to implement. In this article, we’ll cover how to copy text to the clipboard with practical a example using a React component, suitable for a Next.js app.

1. Copying Text to Clipboard

Copying text to the clipboard is the most straightforward use case, and the navigator.clipboard.writeText API handles this elegantly. Here’s a simple React component that demonstrate copying text to the clipboard.

Component "CopyTextComponent" is not available. Please define it in the MDX components.

"use client";

const CopyTextComponent = () => {
  const handleCopyText = (text: string) => {
    navigator.clipboard.writeText(text).then(
      () => {
        alert("Text copied to clipboard!");
      },
      (err) => {
        alert("Failed to copy text.");
      }
    );
  };

  const text = "Hello, world!";

  return (
    <div className="pb-6">
      <div className="px-6 py-6 bg-gray-900 flex flex-col gap-2 rounded">
        <p>Click the button to copy the text below:</p>
        <div className="text-xl">{text}</div>
        <div>
          <button
            className="border rounded px-2 py-1 bg-gray-800"
            type="button"
            onClick={() => handleCopyText(text)}
          >
            Copy Text
          </button>
        </div>
      </div>
    </div>
  );
};

export default CopyTextComponent;

This component allows users to click a button to copy a hardcoded string to the clipboard.

Tags
#copy#text#image#file#copy and paste