Dentro do diretório /hooks
crie o useCopyToClipboard.js
:
import { useState, useEffect, useCallback } from "react";const useCopyToClipboard = (resetCopiedInterval = 1500) => {const [isCopied, setIsCopied] = useState(false);const copyToClipboard = (text) => {const el = document.createElement("textarea");el.value = text;el.setAttribute("readonly", "");el.style.position = "absolute";el.style.left = "-99999px";document.body.appendChild(el);el.select();const success = document.execCommand("copy");document.body.removeChild(el);return success;};const handleCopy = useCallback((text) => {copyToClipboard(text);setIsCopied(true);}, []);useEffect(() => {let timeout;if (isCopied && resetCopiedInterval) {timeout = setTimeout(() => setIsCopied(false), resetCopiedInterval);}return () => {clearTimeout(timeout);};}, [isCopied, resetCopiedInterval]);return [isCopied, handleCopy];};export default useCopyToClipboard;
E importe o useCopyToClipboard.js
dentro do App.js:
import "./styles.css";import useCopyToClipboard from "./hooks/useCopyToClipboard";export default function App() {const [isCopied, handleCopy] = useCopyToClipboard();const text = "texto hello world...";return (<div className="App"><h4>Clique no botão para copiar o texto</h4><p>{text}</p><button onClick={() => handleCopy(text)}>Copiar texto</button><p>{isCopied ? "Copiado!" : ""}</p></div>);}
Resultado: