Last active
July 6, 2023 20:06
-
-
Save kinxori/21a90c335cd9f2e4a8880d3dabe61c64 to your computer and use it in GitHub Desktop.
React component to copy an specific text to device's clipboard. Using "navigator.clipboard" and adding visual feedback after 5 seconds of copied.
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
export default function ContactPage() { | |
const [clipboardIsCopy, setClipboardIsCopy] = useState(false); | |
const textToClipBoard = useRef(""); | |
const handleClipboardState = () => { | |
const text = textToClipBoard.current.?textContent; | |
navigator.clipboard.writeText(text); | |
setClipboardIsCopy(!clipboardIsCopy); | |
setTimeout(() => { | |
setClipboardIsCopy(false); | |
}, 5000); | |
}; | |
return ( | |
<> | |
<div> | |
<p> | |
My email: <i ref={textToClipBoard}> emailtocopy@gmail.com </i> | |
</p> | |
</div> | |
<button onClick={handleClipboardState}> | |
{clipboardIsCopy ? ( | |
<span> | |
Copiado <i className="fa-solid fa-check"></i> | |
</span> | |
) : ( | |
<span> | |
Copiar <i className="fa-regular fa-clipboard"></i> | |
</span> | |
)} | |
</button> | |
</> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment