Skip to content

useClipboard

Hook to handle Clipboard.

N.B.: The hook has the same compatibility issues as the Clipboard API for Firefox, i.e. it is currently impossible to read from the clipboard.

See: Clipboard API.

Demo

INFO

  • The component has an internal state val and invokes useClipboard hook with these properties: useValue=true target=ref and dataType=text. It means that hook will return value of type string and write and read functions that handle text data type. The component declares also two functions:
    • copy that invokes write function to write into clipboard text selected.
    • paste that invokes read function to get value from clipboard and setting it to internal stave variable val.
  • ref is attached to a div that contains two buttons COPY and PASTE, that have copy and paste functions respectively to handle their click event and two paragraph texts.
  • Another div is rendered that displays the internal state val and current clipboard values.
Loading demo…
Show source code
tsx
import { useCallback, useRef, useState } from "react";
import { useClipboard } from "../../../..";

export const UseClipboard = () => {
	const ref = useRef<HTMLDivElement>(null);
	const [val, setVal] = useState("");
	const [value, write, read] = useClipboard({ useValue: true, target: ref, dataType: "text" });
	const copy = useCallback(async () => {
		await write(getSelection()?.toString() || "");
	}, [write])

	const paste = useCallback(async () => {
		const value = await read();
		setVal(value as string);
	}, [read])

	return <div style={{ display: "grid", gridTemplateColumns: "50% 50%", columnGap: 15 }}>
		<div ref={ref} style={{ position: "relative", border: "1px solid lightgray" }}>
			<div style={{ display: "grid", gridTemplateColumns: "100px 100px", justifyContent: "center", columnGap: 15 }}>
				<button onClick={copy}>Copy</button>
				<button onClick={paste}>Paste</button>
			</div>
			<div>
				<p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Incidunt repudiandae fugit distinctio molestiae excepturi ex qui, impedit iste odit. Explicabo quis reprehenderit voluptates reiciendis nostrum minima autem temporibus sint doloribus</p>
			</div>
			<div>
				<p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Incidunt repudiandae fugit distinctio molestiae excepturi ex qui, impedit iste odit. Explicabo quis reprehenderit voluptates reiciendis nostrum minima autem temporibus sint doloribus</p>
			</div>
		</div>
		<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", columnGap: 15, border: "1px solid lightgray" }}>
			<div style={{ textAlign: "left", padding: "0 1em", maxHeight: 300, overflow: "auto" }}>
				<p><strong>Use ClipboardValue:</strong></p>
				<pre>{JSON.stringify(value, null, 2)}</pre>
			</div>
			<div style={{ textAlign: "left", padding: "0 1em", maxHeight: 300, overflow: "auto" }}>
				<p><strong>Internal value:</strong></p>
				<pre>{JSON.stringify(val, null, 2)}</pre>
			</div>
		</div>
	</div>
}

Types

UseClipboardProps

Props accepted by useClipboard.

PropertyTypeRequiredDescription
useValuebooleanreturn a value with current clipboard value or not
dataType"text" \| "any"target on which delimiter handling
targetRefObject<HTMLElement> \| HTMLElementdata type handling. Based on it, Hook will return the functions for writing or reading text only or any type of data.

UseClipboardResult

Result returned by useClipboard.

  • [0] — curren value.
  • [1] — function to write value to the clipboard asynchronously..
  • [2] — function to read value from the clipboard asynchronously. Returns the current clipboard contents.

OR

  • [0] — function to write value to the clipboard asynchronously..
  • [1] — function to read value from the clipboard asynchronously. Returns the current clipboard contents.
ts
export type UseClipboardResult =
	| [
		/** Current value */
		string,
		/**
		 * Write value to the clipboard asynchronously.
		 * @param value - The value to copy to the clipboard.
		 */
		(value: string) => Promise<void>,
		/** Read value from the clipboard asynchronously. Returns the current clipboard contents. */
		() => Promise<string>
	]
	| [string | Blob | (string | Blob)[], (blob: Blob | Blob[]) => Promise<void>, () => Promise<string | Blob | (string | Blob)[]>]
	| [(text: string) => Promise<void>, () => Promise<string>]
	| [(blob: Blob | Blob[]) => Promise<void>, () => Promise<string | Blob | (string | Blob)[]>];

Released under the MIT License.