🎁 The Js-Craft Guide to React is now available with a 30% 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.

10 Javascript AI projects with Langchain & React

Not sure what to build? Dive in with these Javascript AI projects! Learn how to build LLM powered apps using Langchain.js and React! Connect your apps to LLMs such as OpenAI, create agents, use vector databases, or setup AI context.

10 Javascript AI projects with Langchain & React

Not sure what to build? Dive in with these Javascript AI projects! Learn how to build LLM powered apps using Langchain.js and React! Connect your apps to LLMs such as OpenAI, create agents, use vector databases, or setup AI context.


Leave a Reply

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

📘 The Guide to React Home Screencasts Best of Newsletter Search X

📘 - 10 Javascript AI projects with React and LangChain

Hi friend! Before you go, just wanted to let you know about the 10 Javascript AI projects ideas with React and LangChain FREE ebook.

One of the best ways to learn is by doing the work. Choose from these 10 project ideas and start working on topics such as:

  • How does LangChain work
  • Connecting to OpenAI LLM
  • Create AI Agents
  • Simple and Sequential Chains
  • Adding Memory (Chat Context)
  • Prompt Templates
  • Using OutputParsers and Tools for Agents
  • Work with Documents and more...

Keep building and see the new capabilities LLM models can add to your React app! Get all projects as an ebook right to your inbox!

X