Movatterモバイル変換


[0]ホーム

URL:


usehooks-ts

Getting Started

IntroductionMigrate to v3

Hooks

useBooleanuseClickAnyWhereuseCopyToClipboarduseCountdownuseCounteruseDarkModeuseDebounceCallbackuseDebounceValueuseDocumentTitleuseEventCallbackuseEventListeneruseHoveruseIntersectionObserveruseIntervaluseIsClientuseIsMounteduseIsomorphicLayoutEffectuseLocalStorageuseMapuseMediaQueryuseOnClickOutsideuseReadLocalStorageuseResizeObserveruseScreenuseScriptuseScrollLockuseSessionStorageuseStepuseTernaryDarkModeuseTimeoutuseToggleuseUnmountuseWindowSize

useCopyToClipboard


Custom hook that copies text to the clipboard using theClipboard API.

Usage

import{ useCopyToClipboard}from'usehooks-ts'exportdefaultfunctionComponent(){const[copiedText, copy]=useCopyToClipboard()consthandleCopy=(text:string)=>()=>{copy(text).then(()=>{console.log('Copied!',{ text})}).catch(error=>{console.error('Failed to copy!', error)})}return(<><h1>Click to copy:</h1><divstyle={{ display:'flex'}}><buttononClick={handleCopy('A')}>A</button><buttononClick={handleCopy('B')}>B</button><buttononClick={handleCopy('C')}>C</button></div><p>Copied value:{copiedText??'Nothing is copied yet!'}</p></>)}

API

useCopyToClipboard(): [CopiedValue,CopyFn]

Custom hook that copies text to the clipboard using theClipboard API.

Returns

[CopiedValue,CopyFn]

An tuple containing the copied text and a function to copy text to the clipboard.

Type aliases

ƬCopiedValue:string |null

The copied text asstring ornull if nothing has been copied yet.

ƬCopyFn: (text:string) =>Promise<boolean>

Function to copy text to the clipboard.

Type declaration

▸ (text):Promise<boolean>

Parameters
NameTypeDescription
textstringThe text to copy to the clipboard.
Returns

Promise<boolean>

Hook

import{ useCallback, useState}from'react'typeCopiedValue=string|nulltypeCopyFn=(text:string)=>Promise<boolean>exportfunctionuseCopyToClipboard():[CopiedValue, CopyFn]{const[copiedText, setCopiedText]=useState<CopiedValue>(null)const copy: CopyFn=useCallback(async text=>{if(!navigator?.clipboard){console.warn('Clipboard not supported')returnfalse}// Try to save to clipboard then save it in the state if workedtry{await navigator.clipboard.writeText(text)setCopiedText(text)returntrue}catch(error){console.warn('Copy failed', error)setCopiedText(null)returnfalse}},[])return[copiedText, copy]}

useClickAnyWhereuseCountdown

On This Page


[8]ページ先頭

©2009-2025 Movatter.jp