JAVASCRIPT

Integrate Copy-to-Clipboard Functionality with `useClipboard` Hook

Enable seamless copy-to-clipboard functionality in your React apps using a custom `useClipboard` hook, enhancing user interaction for sharing or data transfer.

import React, { useState, useEffect } from 'react';

function useClipboard() {
  const [isCopied, setIsCopied] = useState(false);
  const [error, setError] = useState(null);

  const copyToClipboard = async (text) => {
    try {
      await navigator.clipboard.writeText(text);
      setIsCopied(true);
      setError(null);
    } catch (err) {
      setError(err);
      setIsCopied(false);
    }
  };

  // Reset 'isCopied' after a short delay
  useEffect(() => {
    if (isCopied) {
      const timeout = setTimeout(() => setIsCopied(false), 2000);
      return () => clearTimeout(timeout);
    }
  }, [isCopied]);

  return [copyToClipboard, isCopied, error];
}

function ShareableText() {
  const textToCopy = 'Hello, React hooks!';
  const [copy, isCopied, error] = useClipboard();

  return (
    <div>
      <p>{textToCopy}</p>
      <button onClick={() => copy(textToCopy)}>
        {isCopied ? 'Copied!' : 'Copy to Clipboard'}
      </button>
      {error && <p style={{ color: 'red' }}>Error: {error.message}</p>}
    </div>
  );
}

export default ShareableText;
How it works: This `useClipboard` hook provides an easy way to add 'copy to clipboard' functionality. It exposes a `copyToClipboard` function, a `isCopied` boolean state to indicate success, and an `error` state for failures. It leverages the modern `navigator.clipboard.writeText` API (which requires HTTPS or localhost). A `useEffect` hook automatically resets the `isCopied` state after a brief period, providing visual feedback without manual intervention.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs