Your destination for complete Tech news

how to copy text to the clipboard in React JS?

3.04K 0
< 1 min read

You can use the Clipboard API to copy text to the clipboard in a React application. Here’s an example of how to do this:

import React, { useState } from 'react';

function App() {
  const [textToCopy, setTextToCopy] = useState('');
  const [copySuccess, setCopySuccess] = useState(false);

  const handleCopyClick = () => {
      .then(() => {
      .catch((error) => {
        console.error('Failed to copy: ', error);

  return (
        onChange={(e) => setTextToCopy(}
        placeholder="Enter text to copy"
      <button onClick={handleCopyClick}>Copy to Clipboard</button>
      {copySuccess && <p>Text copied successfully!</p>}

export default App;

In this example, the navigator.clipboard.writeText(text) function is used to write the provided text to the clipboard. When the button is clicked, the handleCopyClick function is called, which attempts to copy the textToCopy value to the clipboard. If the copy is successful, it sets the copySuccess state to true and displays a success message.

Please note that the Clipboard API has certain browser compatibility considerations, so make sure to test this functionality on different browsers to ensure it works as expected.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.