šŸ“™ Understanding Neuronal Networks presale is now open - 20% off discount!

React copy text to clipboard

In order to implement a copy text to clipboard functionality in React the easiest solution is to use the navigator.clipboard API.

Let’s say we want to build a simple React component that automatically copies a given text to the clipboard:
React copy text to clipboard

The above example will be implemented by this code:

const App = () => {
    const [code, setCode] = useState("123456789")
    const [clipboardVal, setClipboardVal] = useState(null)

    const copyOperation = ()=> {
        navigator.clipboard.writeText(code)
            .then(() => setClipboardVal(code))
            .catch((e) => {
                setClipboardVal(null)
                console.warn('Clipboard error:' + e)
            })
    }

    return (<div>
        <input type="text" value={code} disabled  />
        <button onClick={copyOperation}>Copy Code</button>
        {clipboardVal && <p>āœ… Copied to clipboard: {clipboardVal}</p>}
    </div>)
}

The whole magic happens in the copyOperation() function, where we use the writeText() method of the browser’s navigator clipboard API.

Note that the writeText() method is async, so be sure to communicate the success state only when the promise is resolved, and also cover eventual errors:

navigator.clipboard.writeText(code)
        .then(() => setClipboardVal(code))
        .catch((e) => {
            setClipboardVal(null)
            console.warn('Clipboard error:' + e)
        })

You can check out the full code in the Github repository and see the live example here.

This article focuses just on text data. I’ve also made this example about how to copy and paste images from clipboard with React.

Using a copy text to clipboard React hook

We can easily extract the copy text to the clipboard in its own useTextToClipboard() React hook:

const useTextToClipboard= () => {
    const [value, setValue] = useState(null)

    const copy = (data) => {
        navigator.clipboard.writeText(data)
            .then(() => setValue(data))
            .catch((e) => {
                setClipboardVal(null)
                console.warn('Clipboard error:' + e)
            })
    }

    return [value, copy]
}

And to use the useTextToClipboard() hook we can do as follows:

const App = () => {
    const [code, setCode] = useState("123456789")
    const [clipboardVal, copyToCliboard] = useTextToClipboard()

    return (<div>
        <input type="text" value={code} disabled  />
        <button onClick={()=> copyToCliboard(code) }>Copy Code</button>
        {clipboardVal && <p>āœ… Copied to clipboard: {clipboardVal}</p>}
    </div>)
}

If you are interested I’ve also written about how to use the Clipboard API to copy text in vanilla Javascript.

Browser support for navigator clipboard

The browser support is excellent for the navigator clipboard, being fully supported and available in all major browsers.

šŸ“– Neural Networks from Scratch - Presale

I'm writing a book about the timeless foundational concepts of neural networks for JavaScript developers. Go from if-else to weights and biases by building tiny AI models from scratch!

šŸ“– Neural Networks from Scratch - Presale

I'm writing a book about the timeless foundational concepts of neural networks for JavaScript developers. Go from if-else to weights and biases by building tiny AI models from scratch!


Leave a Reply

Your email address will not be published. Required fields are marked *