UIPackage React Native
Search

Copy Button

Action button that copies text with expo-clipboard, guards rapid presses, and shows temporary confirmation only after a verified write.

Install

First install? Set up the registry in your app.

npx --yes --package=https://native.uipkge.dev/cli/uipkge-native-0.1.1.tgz uipkge-native add copy-button

Source files

Expand a file to read the source the installer copies into your app.

components/ui/copy-button/CopyButton.tsx
import * as React from 'react'
import type { GestureResponderEvent } from 'react-native'
import { setStringAsync } from 'expo-clipboard'
import { Button, type ButtonProps } from '@/components/ui/button'

export interface CopyButtonProps extends ButtonProps {
  /** Text written to the system clipboard when pressed. */
  value: string
  /** Label shown briefly after a confirmed clipboard write. Defaults to `'Copied'`. */
  copiedLabel?: React.ReactNode
  /** Milliseconds to display `copiedLabel` before restoring `children`. Defaults to `2000`. */
  copiedDuration?: number
  /** Called only when `expo-clipboard` confirms the write (`true`). */
  onCopied?: (value: string) => void
  /** Called when `expo-clipboard` returns `false` or rejects. */
  onError?: (error: Error) => void
}

/**
 * Copies `value` to the clipboard using `expo-clipboard`.
 *
 * Bare React Native apps require `expo-modules` (Expo Modules autolinking) to use `expo-clipboard`.
 * On web, clipboard writes require a secure context (HTTPS or localhost) and an
 * active user gesture; otherwise `setStringAsync` resolves to `false` or rejects.
 */
const CopyButton = React.forwardRef<React.ComponentRef<typeof Button>, CopyButtonProps>(
  (
    {
      value,
      copiedLabel = 'Copied',
      copiedDuration = 2000,
      onCopied,
      onError,
      onPress,
      disabled,
      loading = false,
      children = 'Copy',
      accessibilityLiveRegion = 'polite',
      ...props
    },
    ref,
  ) => {
    const [pending, setPending] = React.useState(false)
    const [copied, setCopied] = React.useState(false)
    const mountedRef = React.useRef(true)
    const pendingRef = React.useRef(false)
    const valueGenerationRef = React.useRef(0)
    const timerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null)
    const previousValueRef = React.useRef(value)

    React.useEffect(() => {
      mountedRef.current = true
      return () => {
        mountedRef.current = false
        valueGenerationRef.current += 1
        if (timerRef.current !== null) {
          clearTimeout(timerRef.current)
          timerRef.current = null
        }
      }
    }, [])

    React.useEffect(() => {
      if (previousValueRef.current === value) return
      previousValueRef.current = value
      valueGenerationRef.current += 1
      if (timerRef.current !== null) {
        clearTimeout(timerRef.current)
        timerRef.current = null
      }
      setCopied(false)
    }, [value])

    async function handlePress(event: GestureResponderEvent) {
      if (disabled || loading || pendingRef.current) return
      onPress?.(event)
      if (event?.defaultPrevented) return

      pendingRef.current = true
      setPending(true)
      const generation = valueGenerationRef.current
      let ok = false
      let nativeError: Error | undefined

      try {
        ok = (await setStringAsync(value)) === true
      } catch (error) {
        nativeError = error instanceof Error ? error : new Error(String(error))
      }

      pendingRef.current = false
      if (!mountedRef.current) return
      setPending(false)

      if (valueGenerationRef.current !== generation) return

      if (nativeError || !ok) {
        setCopied(false)
        onError?.(nativeError ?? new Error('Unable to copy to clipboard.'))
        return
      }

      setCopied(true)
      if (timerRef.current !== null) {
        clearTimeout(timerRef.current)
        timerRef.current = null
      }
      if (Number.isFinite(copiedDuration) && copiedDuration > 0) {
        timerRef.current = setTimeout(() => {
          timerRef.current = null
          if (mountedRef.current) setCopied(false)
        }, copiedDuration)
      }
      onCopied?.(value)
    }

    return (
      <Button
        ref={ref}
        disabled={disabled}
        loading={loading || pending}
        accessibilityLiveRegion={accessibilityLiveRegion}
        onPress={handlePress}
        {...props}
      >
        {copied ? copiedLabel : children}
      </Button>
    )
  },
)
CopyButton.displayName = 'CopyButton'

export { CopyButton }
components/ui/copy-button/index.ts
export { CopyButton, type CopyButtonProps } from './CopyButton'

Dependencies

Registry items

npm packages

  • expo-clipboard
Browse controls and interactions