This repository has been archived by the owner on Aug 7, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* copy to clipboard feature added * updated handleCopyClick function to use async await * refactored the copy to clipboard function added react-children-utilities
- Loading branch information
1 parent
e42cf06
commit 5fdbcfb
Showing
4 changed files
with
73 additions
and
3 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
import React, { useState } from "react"; | ||
import { onlyText } from "react-children-utilities"; | ||
|
||
const ClipboardCopy = ({children}) => { | ||
const [isCopied, setIsCopied] = useState(false); | ||
|
||
async function copyTextToClipboard(text) { | ||
if ("clipboard" in navigator) { | ||
return await navigator.clipboard.writeText(text); | ||
} else { | ||
return document.execCommand("copy", true, text); | ||
} | ||
} | ||
|
||
const handleCopyClick = async () => { | ||
try { | ||
await copyTextToClipboard(onlyText(children)); | ||
setIsCopied(true); | ||
setTimeout(() => { | ||
setIsCopied(false); | ||
}, 1500); | ||
} catch (error) { | ||
console.log(err); | ||
} | ||
}; | ||
|
||
return ( | ||
<div className="relative"> | ||
<div className="absolute flex items-center space-x-2 top-0 right-0 m-2"> | ||
<button | ||
type="button" | ||
aria-label="Copy to Clipboard" | ||
onClick={handleCopyClick} | ||
className="transition rounded-md flex items-center justify-center text-center px-2 focus:outline-none fade-in group-hover:flex" | ||
> | ||
{isCopied ? ( | ||
<span className="text-green-500 text-sm">Copied!</span> | ||
) : ( | ||
<span className="text-gray-500 text-sm">Copy</span> | ||
)} | ||
</button> | ||
</div> | ||
{children} | ||
</div> | ||
); | ||
}; | ||
|
||
export default ClipboardCopy; |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
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
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