In web apps, it's common to copy text to the clipboard, so React.js gives us quick ways to do this. In this article, you will learn two ways to copy text to the clipboard in React.js. Whether you're new or experienced, you'll learn how to add clipboard features to your React.js apps.
So let's get started.
If you haven't created a project yet, initiate your React app using this command: npx create-react-app myapp. And run your project.
1. Using the navigator.clipboard API
The navigator.clipboard API offers a simple method to copy text to the clipboard in modern web browsers.
In this project, I've included React Toastify, an optional feature. It enhances the user experience by displaying a notification when text is copied, improving the UI design. If you're interested, you can install React Toastify using the following command; if not, then skip it.
// For npm
npm install react-toastify
// For yarn
yarn add react-toastify
Start by making a new component called "ClipboardCopy.jsx" in your src folder. Then, add this code.
// ClipboardCopy.jsx
import React, { useState } from 'react';
import { toast } from 'react-toastify';
import './App.css';
function ClipboardCopy() {
const [text, setText] = useState('');
const [copySuccess, setCopySuccess] = useState('');
const handleChange = (event) => {
setText(event.target.value);
setCopySuccess(''); // Reset copy success message when text changes
};
const handleCopy = async () => {
try {
await navigator.clipboard.writeText(text);
setCopySuccess('Copied to clipboard!'); // Indicate successful copy
setTimeout(() => {
setCopySuccess('');
}, 2000);
toast.success("Login Successful!", { position: "top-right" });
} catch (err) {
console.error('Failed to copy: ', err);
}
};
return (
<div className="clipboard-container">
<input
type="text"
value={text}
onChange={handleChange}
placeholder="Enter text to copy"
className="input-field"
/>
<button onClick={handleCopy} className="copy-button">
Copy
</button>
{copySuccess && <div className="copy-success">{copySuccess}</div>}
</div>
);
}
export default ClipboardCopy;
In this code, we have created a React component called ClipboardCopy that allows users to copy text to the clipboard. It uses React's state management (useState) to track the input text and copy the success status.
When the "Copy" button is clicked, it attempts to copy the text to the clipboard using the navigator.clipboard.writeText() method. If successful, it updates the UI to show a success message and displays a toast notification using React Toastify.
Now add this code in your App.js file to import ClipboardCopy and display its UI in the browser.
// App.js
import { ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import ClipboardCopy from './ClipboardCopy';
import './App.css'
function App() {
return (
<div className="App">
<ToastContainer />
<h1>Copy Text to Clipboard</h1>
<ClipboardCopy />
</div>
);
}
export default App;
In this code, we have set up a React application. It imports the necessary components and styling, including the Toast notification system. The main component (App) renders a heading and includes the ClipboardCopy component for copying text to the clipboard.
App.css file (optional)
/* App.css */
body {
font-family: sans-serif;
background-color: #e7e7e7;
}
h1 {
text-align: center;
}
.clipboard-container {
display: flex;
align-items: center;
flex-direction: column;
}
.input-field {
width: 300px;
height: 30px;
padding: 8px;
border: 1px solid #ccc;
border-radius: 5px;
margin-bottom: 10px;
}
.copy-button {
width: 120px;
height: 40px;
background-color: #007bff;
color: #fff;
border: none;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.2s ease;
}
.copy-button:hover {
background-color: #0056b3;
}
.copy-success {
color: green;
margin-top: 10px;
font-size: 14px;
}
I've improved the look with CSS styling to make the UI design better. You can improve this UI by adding more styles to this project.
2. Using the react-copy-to-clipboard package
Alternatively, you can use the react-copy-to-clipboard package, which simplifies the process of copying text to the clipboard in React.js applications.
To begin, you need to install the react-copy-to-clipboard package. Open your terminal and run the following command:
npm install --save react-copy-to-clipboard
This command will install the react-copy-to-clipboard package and add it to your project's dependencies.
Now, let's create a React component where we will implement the text copying functionality. Create a new file named ClipboardCopy.jsx in your project's src directory.
// ClipboardCopy.js
import React, { useState } from 'react';
import CopyToClipboard from 'react-copy-to-clipboard';
function ClipboardCopy() {
// State to store the text to be copied
const [text, setText] = useState('');
// State to track if the text has been copied
const [copied, setCopied] = useState(false);
// Function to handle text input change
const handleInputChange = (event) => {
setText(event.target.value);
// Reset copied state when text changes
setCopied(false);
};
// Function to handle text copy
const handleCopy = () => {
// Set copied state to true when text is copied
setCopied(true);
};
return (
<div>
{/* Input field to enter text */}
<input
type="text"
value={text}
onChange={handleInputChange}
placeholder="Enter text to copy"
/>
{/* Copy button using react-copy-to-clipboard */}
<CopyToClipboard text={text} onCopy={handleCopy}>
<button>Copy Text</button>
</CopyToClipboard>
{/* Display message when text is copied */}
{copied && <div style={{ color: 'green' }}>Text copied to clipboard!</div>}
</div>
);
}
export default ClipboardCopy;
This ClipboardCopy component enables users to input text and copy it to the clipboard using the react-copy-to-clipboard library. It maintains two state variables: text for storing input text and copied to track successful copying.
When users type in the input field, handleInputChange updates the text state and resets copied to false. Clicking the copy button triggers handleCopy, setting copied to true. If copying succeeds, a green success message appears below the button.
Now, you can use the ClipboardCopy component in your application wherever you need text-copying functionality. For example, you can include it in your main component (App.js).
// App.js
import React from 'react';
import ClipboardCopy from './ClipboardCopy';
function App() {
return (
<div className="App">
<h1>Copy Text to Clipboard</h1>
<ClipboardCopy />
</div>
);
}
export default App;
In this code, I've simply demonstrated how to copy text to the clipboard without any fancy styling or React Toastify features. But just like I showed you in the previous example, you can make it better by adding those. Think of this as a task to improve your skills.
Conclusion
In this guide, we've looked at two ways to copy text in React.js: using the navigator.clipboard API and the react-copy-to-clipboard package. Both methods are simple, you can use them according to your project and choose your favorite method. Becoming a professional developer requires knowing another way to do the same thing.
If you have any questions regarding this article or any other web development, then you can ask them in the question box given below, and you will get the answer as soon as possible.