Having the following code snippet:
<div>
<Input
id='id'
disabled
value='test'
/>
<Button
onClick={copyToClipboard}
/>
</div>
The button, when clicked, must copy the value from input, which is already set to test
.
So, copyToClipboard
must perform the operation:
const copyToClipboard = () => {
...
};
How I've tried:
import { useRef, useState } from 'react';
...
const [copySuccess, setCopySuccess] = useState('');
const textAreaRef = useRef(null);
function copyToClipboard(e) {
textAreaRef.current.select();
document.execCommand('copy');
e.target.focus();
setCopySuccess('Copied!');
}
...
<div>
<Input
ref={textAreaRef}
id='id'
value='test'
/>
<Button
onClick={copyToClipboard}
/>
</div>
It has an error saying: Object is possibly 'null'.ts(2531)
for textAreaRef.current.select();
. I'm using React with Typescript.