Implementing a custom hook for handling copy to clipboard functionality in React involves using the Clipboard API and creating a reusable hook that encapsulates the logic for copying text to the clipboard. Here's how you can create such a custom hook:
Create a new file for your custom hook: Start by creating a new file, such as useClipboard.js
, where you'll define your custom hook.
Import necessary dependencies: Import useCallback
hook from React. This will be used to create a memoized callback function for copying text to the clipboard.
Define the custom hook: Write the logic for your custom hook. The hook will return a function that can be called to copy text to the clipboard.
Here's an example implementation of the custom hook:
javascriptimport { useCallback } from 'react';
const useClipboard = () => {
const copyToClipboard = useCallback((text) => {
if (!navigator.clipboard) {
// Fallback to older method if Clipboard API is not available
const textArea = document.createElement('textarea');
textArea.value = text;
document.body.appendChild(textArea);
textArea.select();
document.execCommand('copy');
document.body.removeChild(textArea);
return;
}
navigator.clipboard.writeText(text)
.then(() => {
console.log('Text copied to clipboard');
})
.catch((error) => {
console.error('Failed to copy text to clipboard:', error);
});
}, []);
return copyToClipboard;
};
export default useClipboard;
useClipboard
hook and use it in your component.Here's an example of how you can use the useClipboard
hook in a component:
javascriptimport React from 'react';
import useClipboard from './useClipboard';
const CopyToClipboardButton = ({ text }) => {
const copyToClipboard = useClipboard();
const handleCopyClick = () => {
copyToClipboard(text);
};
return (
<button onClick={handleCopyClick}>Copy to Clipboard</button>
);
};
export default CopyToClipboardButton;
In this example, the CopyToClipboardButton
component uses the useClipboard
hook to get the copyToClipboard
function, which it calls when the button is clicked. The copyToClipboard
function takes a text argument, which is the text to be copied to the clipboard.
With this setup, you have a reusable custom hook for handling copy to clipboard functionality in your React components. You can use it wherever you need to provide copy functionality.