Last active
July 24, 2021 22:05
-
-
Save j4viermora/62939aa54ac9fbf1b3d73148c1c89f34 to your computer and use it in GitHub Desktop.
Small utility to copy text to clipboard in reactjs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Now, ruturn status and handleCopy like array, this allows use the function several times in the same component, something like useState