Skip to content

Instantly share code, notes, and snippets.

@cameronp98
Created May 24, 2020 20:07
Show Gist options
  • Save cameronp98/81eea885febe5261f5f64072a86616fa to your computer and use it in GitHub Desktop.
Save cameronp98/81eea885febe5261f5f64072a86616fa to your computer and use it in GitHub Desktop.
React button to copy text to clipboard using a hidden input field
import React from 'react'
function CopyButton({ value }) {
const hiddenInput = React.createRef()
function handleClick() {
hiddenInput.current.select()
hiddenInput.current.setSelectionRange(0, 99999)
document.execCommand('copy')
console.log(`copied '${value}'`)
}
return (
<div>
<button onClick={handleClick}>Copy Text</button>
<input readOnly hidden value={value} ref={hiddenInput} />
</div>
)
}
export default CopyButton
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment