OWolf

2024-10-01 Web Development

Copy to Clipboard for Text in JavaScript

By 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.

Click the button to copy the text below:

Hello, world!
jsx
"use client";

import React from "react";

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.