useClipboard

React hook to copy to the clipboard.

import { useState } from 'react'

export const useClipboard = () => {
  const [copiedText, setCopiedText] = useState<string | null>('')

  const copyToClipboard = (value: string) => {
    return new Promise<string>((resolve, reject) => {
      try {
        if (navigator?.clipboard?.writeText) {
          navigator.clipboard
            .writeText(value)
            .then(() => {
              setCopiedText(value)
              resolve(value)
            })
            .catch((e) => {
              setCopiedText(null)
              reject(e)
            })
        } else {
          setCopiedText(null)
          throw new Error('Clipboard not supported')
        }
      } catch (e) {
        reject(e)
      }
    })
  }

  return { copiedText, copyToClipboard }
}

React 16.8 or higher

  • Name
    copiedText
    Type
    string | null
    Description

    The text currently copied to the clipboard. If null, it means that the copyToClipboard function had an error.

  • Name
    copyToClipboard
    Type
    function
    Description

    Copy a text to the clipboard. This function accepts the text to copy and returns a promise.

import { useClipboard } from './hooks/useClipboard'
import { useRef } from 'react'

const App = () => {
  const { copiedText, copyToClipboard } = useClipboard()
  const inputRef = useRef<HTMLInputElement>(null)

  const handleClick = () => {
    copyToClipboard(inputRef.current?.value || '')
      .then(() => alert('Copied!'))
      .catch(() => alert('Failed!'))
  }

  return (
    <div>
      <input type="text" ref={inputRef} />
      <button onClick={handleClick}>Copy input text</button>
    </div>
  )
}

export default App

Here are some use cases where this React hook is useful:

  • Enabling users to copy text to the clipboard in a web-based note-taking app
  • Implementing a "Share" button in a web app to copy a link to the clipboard
  • Facilitating easy copying of coupon codes in an e-commerce website
  • Allowing users to quickly copy error messages for reporting in a bug tracking tool
  • Implementing a "Copy to Clipboard" feature for sharing code snippets in a developer community platform