React component and hook for copying text from an HTML element.
If you prefer npm:
npm i react-copy-snippet
If you prefer yarn:
yarn add react-copy-snippet
import CopySnippet from 'react-copy-snippet'
import { useRef } from 'react'
const Demo = () => {
const snipRef = useRef(null)
return (
<div>
<pre ref={snipRef}>
this is an example text that is being copied.
</pre>
<CopySnippet ref={snipRef} />
</div>
)
}
export default Demo
if you just want to copy some text
import CopySnippet from 'react-copy-snippet'
const Demo = () => {
return (
<div>
<CopySnippet text="hello world" />
</div>
)
}
export default Demo
we also have useCopyToClipboard hook
import CopySnippet, { useCopyToClipboard } from 'react-copy-snippet'
import { useRef } from 'react'
const Demo = () => {
const snipRef = useRef(null)
const {handleCopy, isCopied} = useCopyToClipboard({textContent: "hello world"})
return (
<div>
<pre ref={snipRef}>
this is an example text that is being copied.
</pre>
<CopySnippet ref={snipRef} />
<button onClick={handleCopy}>{isCopied ? "copied!" : "copy"}</button>
</div>
)
}
export default Demo
Name | Type | Description |
---|---|---|
text |
string | The text content to be copied when using the component. |
ref |
React.RefObject | Reference to the HTML element from which to copy text. |
Any HTML Attributes | - | Any additional HTML attributes to be passed to the underlying <button> element. |