Skip to content

Instantly share code, notes, and snippets.

@j4viermora
Last active July 24, 2021 22:05
Show Gist options
  • Save j4viermora/62939aa54ac9fbf1b3d73148c1c89f34 to your computer and use it in GitHub Desktop.
Save j4viermora/62939aa54ac9fbf1b3d73148c1c89f34 to your computer and use it in GitHub Desktop.
Small utility to copy text to clipboard in reactjs
import { useState} from 'react';
const copyToClipboard = ( id ="" ) => {
const [status, setStatus] = useState(false)
const deleteMessage = () => {
setTimeout( () => {
setStatus(false)
}, 3000 );
}
const handlerCopy = (e) => {
e.preventDefault();
try {
document.getElementById(`${id}`).focus();
document.execCommand('selectAll');
document.execCommand("copy");
setStatus(true)
deleteMessage()
} catch (error) {
setStatus(false)
}
}
return[
status,
handlerCopy,
]
};
export default copyToClipboard;
@j4viermora
Copy link
Author

Now, ruturn status and handleCopy like array, this allows use the function several times in the same component, something like useState

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment