Skip to content

Clipboard and selection ​

The clipboard and the text selection, as an app with its own context menus uses them.

tsx
import { copyText, readClipboardText, selectAllWithin, selectionWithin } from '@basmilius/react-ui';
tsx
import { useRef, useState } from 'react';
import { Button, copyText, readClipboardText, selectAllWithin, selectionWithin } from '@basmilius/react-ui';

export default function ClipboardDemo() {
    const block = useRef<HTMLParagraphElement>(null);
    const [read, setRead] = useState('');

    return (
        <div className="flex w-full max-w-md flex-col gap-3">
            <p ref={block} className="rounded-lg border border-border bg-surface p-3 font-mono text-code text-text select-text">
                git remote add origin git@github.com:basmilius/react-ui.git
            </p>
            <div className="flex flex-wrap gap-2">
                <Button variant="secondary" size="sm" onClick={() => selectAllWithin(block.current)}>
                    Select all
                </Button>
                <Button variant="secondary" size="sm" onClick={() => copyText(selectionWithin(block.current) || block.current?.textContent || '')}>
                    Copy
                </Button>
                <Button variant="secondary" size="sm" onClick={() => void readClipboardText().then(setRead)}>
                    Read the clipboard
                </Button>
            </div>
            {read !== '' && <p className="text-xs text-text-muted">The clipboard holds: {read}</p>}
        </div>
    );
}

copyText(text) writes text to the clipboard. readClipboardText() answers what is on it, or an empty string when the browser will not say. A browser hands over the clipboard only to a focused document that is allowed to use it, and nobody can do anything about a refusal, so both stay quiet instead of throwing.

selectionWithin(element) answers the selected text, but only when the selection lies inside element. A context menu belongs to the surface the click landed on, and a selection somewhere else is not one that menu can copy. selectAllWithin(element) selects the text of element and nothing else, which is what Cmd+A should do inside a block of text. TextMenu uses both.