Milind Daraniya

How to Copy Text to the Clipboard in React.js?

Published August 31st, 2023 20 min read

Hello, React developers! In this tutorial, we'll explore how to copy text to the clipboard in a React.js application. Providing users with the ability to copy content to the clipboard is a convenient feature for enhancing user experience. We'll walk you through the process step-by-step with a practical example and showcase the output.

Step 1: Set Up a New React Project 
If you don't have a React project yet, you can create one using Create React App (CRA). Open your terminal and run the following command:

npx create-react-app react-copy-to-clipboard-example

Step 2: Create a CopyToClipboard Component 
Now, let's create a new component called CopyToClipboard that will allow us to copy text to the clipboard. Create a file named CopyToClipboard.js in the src directory of your React project:

// src/CopyToClipboard.js
import React, { useState } from 'react';

const CopyToClipboard = () => {
  const [text, setText] = useState('Copy this text to the clipboard!');

  const handleCopy = () => {
    navigator.clipboard.writeText(text)
      .then(() => alert('Text copied to clipboard!'))
      .catch(err => console.error('Error copying text: ', err));
  };

  return (
    <div>
      <h2>Copy to Clipboard Example</h2>
      <p>{text}</p>
      <button onClick={handleCopy}>Copy Text</button>
    </div>
  );
};

export default CopyToClipboard;

Step 3: Render the Component in App.js 
Now, let's render the CopyToClipboard component in the App.js file. Open the App.js file in the src directory and update it as follows:

// src/App.js
import React from 'react';
import CopyToClipboard from './CopyToClipboard';

function App() {
  return (
    <div>
      <h1>React Copy to Clipboard Example</h1>
      <CopyToClipboard />
    </div>
  );
}

export default App;

Step 4: Test the Application 
Start your React development server by running the following command in your project's root directory:

npm start

Visit http://localhost:3000 in your web browser. You should see the "Copy to Clipboard Example" heading, a paragraph containing the text "Copy this text to the clipboard!", and a button labeled "Copy Text".

Step 5: Click the "Copy Text" Button 
Now, click the "Copy Text" button. If the browser supports clipboard access, the text "Copy this text to the clipboard!" will be copied to the clipboard. You should see an alert message indicating that the text has been copied successfully.

Congratulations! 🎉 You've successfully implemented the feature to copy text to the clipboard in your React application.

Output: When you click the "Copy Text" button, you should see an alert message saying "Text copied to clipboard!".

Happy coding, and enjoy building awesome React applications with the copy-to-clipboard feature!