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] = React.useState("123456789")
    const [clipboardVal, setClipboardVal] = React.useState(null)

    const copyOperation = ()=> {
        if (!navigator.clipboard) {
            setClipboardVal(null)
            console.warn('Clipboard not supported')
            return false
        }
        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] = React.useState(null)

    const copy = (data) => {
        if (!navigator.clipboard) {
            setValue(null)
            console.warn('Clipboard not supported')
            return false
        }

        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] = React.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.

📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

📖 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

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

Home Screencasts Best of Newsletter Search X

📖 50 Javascript, React and NextJs Projects

Hi friend! Before you go, just wanted to let you know about the 50 Javascript, React and NextJs Projects FREE ebook.

One of the best ways to learn is by doing the work. Choose from 8 project categories and get started right away:

  • Business & Real-World
  • Games & Puzzles
  • Fun & Interesting
  • Tools & Libraries
  • Personal & Portfolio
  • Project Add-Ons
  • Productivity
  • Clones

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects complete with project briefs and wireframes!

Keep building and level up! Get all projects as an ebook right to your inbox!

X