use-copy is a custom React hook that you can use to easily copy text to the clipboard in your React project. It provides a simple and reusable way to add copy-to-clipboard functionality to your components.
Here's an example of how to use use-copy:
First, install the library using npm or yarn:
npm install use-copy
yarn add use-copy
Import the useCopy hook from use-copy:
import { useCopy } from 'use-copy';
Call the useCopy hook in your component:
function Example() {
const [text, setText] = useState('Hello, world!');
const { copy } = useCopy();
function handleCopy() {
copy(text);
}
return (
<div>
<p>{text}</p>
<button onClick={handleCopy}>Copy to clipboard</button>
</div>
);
}
In this example, the useCopy
hook is called to get the copy
function, which can be used to copy the text
state to the clipboard. When the Copy to clipboard
button is clicked, the handleCopy
function is called, which calls the copy
function with the text to be copied.
Note that the useCopy
hook returnsan object with a copy
function and a status
object. The status
object contains information about the copy operation, such as whether it succeeded or failed, and any error messages.
Customize the useCopy hook by passing options to it. For example, you can set the timeout duration, the message to display when the copy operation succeeds or fails, and more:
const { copy, status } = useCopy({
successDuration: 3000,
successMessage: 'Copied!',
errorMessage: 'Failed to copy',
});
In this example, the successDuration
option sets the duration of the success message to 3 seconds, the successMessage
option sets the message to display when the copy operation succeeds, and the errorMessage
option sets the message to display when the copy operation fails.
It's a simple and reusable solution that saves you from having to write boilerplate code for copying text to the clipboard.
Top comments (0)