useClipboard
useClipboard
is a custom hook that performs the operation of copying a value to the clipboard.
const { onCopy, value, setValue, copied } = useClipboard()
return (
<HStack>
<Input
placeholder="Text to be copied..."
value={value}
onChange={(e) => setValue(e.target.value)}
/>
<Button disabled={!value} onClick={onCopy}>
{copied ? "Copied" : "Copy"}
</Button>
</HStack>
)
If you use this code, you need to add
"use client"
to the top of the file.Usage
import { useClipboard } from "@yamada-ui/react"
import { useClipboard } from "@/components/ui"
import { useClipboard } from "@workspaces/ui"
const { onCopy, value, setValue, copied } = useClipboard("initial value")
Using Initial Values
const { onCopy, value, setValue, copied } = useClipboard("initial value")
return (
<HStack>
<Input
placeholder="text to be copied..."
value={value}
onChange={(e) => setValue(e.target.value)}
/>
<Button disabled={!value} onClick={onCopy}>
{copied ? "Copied" : "Copy"}
</Button>
</HStack>
)
If you use this code, you need to add
"use client"
to the top of the file.Change Timeout
To change the timeout, set a number(milliseconds) to the second argument. The default is 1500
.
const { onCopy, value, setValue, copied } = useClipboard("", 5000)
return (
<HStack>
<Input
placeholder="text to be copied..."
value={value}
onChange={(e) => setValue(e.target.value)}
/>
<Button disabled={!value} onClick={onCopy}>
{copied ? "Copied" : "Copy"}
</Button>
</HStack>
)
If you use this code, you need to add
"use client"
to the top of the file.Copy the Specified Value
const { onCopy, copied } = useClipboard()
const value = "Read-Only Value"
return (
<HStack>
<Input readOnly value={value} />
<Button onClick={() => onCopy(value)}>{copied ? "Copied" : "Copy"}</Button>
</HStack>
)
If you use this code, you need to add
"use client"
to the top of the file.