Search for a command to run...
creating hooks like useClickToCopy() in React projects provides numerous benefits such as code reuse, abstraction, and separation of concerns, which ultimately lead to improved code quality and developer productivity.
useClickToCopy
hook simplifies the implementation of click-to-copy functionality in React projects. Instead of writing repetitive code for handling copy events in various components, developers can use this hook to encapsulate the logic and reuse it throughout the application.import React, { useState } from 'react';
// Define types for parameters and state of the hook
const useClickToCopy = () => {
const [copyState, setCopyState] = useState({ isCopiedError: false, isCopied: false });
const copyToClipboard = ({ textToCopy }) => {
navigator.clipboard
.writeText(textToCopy)
.then(() => {
setCopyState((prevState) => ({ ...prevState, isCopied: true }));
setTimeout(() => {
setCopyState((prevState) => ({ ...prevState, isCopied: false }));
}, 3000);
})
.catch((error) => {
console.error('Failed to copy:', error);
setCopyState((prevState) => ({ ...prevState, isCopied: false, isCopiedError: true }));
});
};
return { copyState, copyToClipboard };
};
export default useClickToCopy;
import { useState } from 'react';
// Define types for parameters and state of the hook
type CopyToClipboardType = {
/**
* The text that you want to copy when the copy event occurs.
*/
textToCopy: string;
};
// Define type for the state of the hook
type CopyStateType = {
// Indicates whether the text has been successfully copied
isCopied: boolean;
// Indicates whether there was an error during copying
isCopiedError: boolean;
};
/**
* A React hook for handling click-to-copy functionality.
*/
const useClickToCopy = () => {
// State to track successful copy
const [copyState, setCopyState] = useState<CopyStateType>({ isCopiedError: false, isCopied: false });
/**
* Copies the specified text to the clipboard.
*
* @param {CopyToClipboardType} param - Object containing the text to copy.
*/
const copyToClipboard = ({ textToCopy }: CopyToClipboardType) => {
// Use the Clipboard API to write text to the clipboard
navigator.clipboard
.writeText(textToCopy)
.then(() => {
// Set isCopied to true on successful copy and reset after a delay
setCopyState((prevState) => ({ ...prevState, isCopied: true }));
setTimeout(() => {
setCopyState((prevState) => ({ ...prevState, isCopied: false }));
}, 3000);
})
.catch((error) => {
// Log and handle copy errors
console.error('Failed to copy:', error);
// Reset the copy state on error and indicate error
setCopyState((prevState) => ({ ...prevState, isCopied: false, isCopiedError: true }));
});
};
// Return the state and copy function for use in components
return { copyState, copyToClipboard };
};
export default useClickToCopy;