How to create a click to copy functionality in react based applications like next.js, remix, CRA by creating useClickToCopy() hook
Created At—2/27/2024
Updated At—5/18/2024
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.
Importance of the Hook in React
- Ease of Use: The
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. - Modularization: Hooks promote modularization by encapsulating related logic into reusable units. This improves code organization and maintainability, making it easier to manage and extend the functionality of the application.
- Abstraction: By abstracting away the implementation details of the copy functionality into a hook, developers can focus on using the feature without concerning themselves with how it works internally. This abstraction enhances code readability and reduces cognitive load.
- Consistency: Using a hook ensures consistency in implementing click-to-copy functionality across different components. Developers can rely on a single source of truth for this feature, which reduces the likelihood of inconsistencies and bugs in the codebase.
- Reusability: Hooks promote code reuse by encapsulating logic that can be shared across multiple components. This reduces redundancy and makes the codebase more efficient and maintainable.
- Abstraction and Encapsulation: Hooks abstract away implementation details, providing a clean interface for interacting with complex functionality. This abstraction enhances code readability and allows developers to focus on the high-level behavior of components.
- Separation of Concerns: Hooks facilitate separation of concerns by isolating specific functionality into modular units. This improves code organization, makes components easier to understand, and simplifies testing.
- Promotes Best Practices: Creating hooks encourages adherence to best practices such as single responsibility principle, DRY (Don't Repeat Yourself) principle, and separation of concerns. This leads to cleaner, more maintainable code.
- Facilitates Composition: Hooks can be composed together to create more complex behavior from simpler building blocks. This enables developers to build powerful and flexible components without introducing unnecessary complexity.
Here's the source code
In JavaScript
useClickToCopy.js
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;
Also for the typescript use case
useClickToCopy.ts
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;