'Copy to clipboard a value from an input in React with Typescript
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.
Solution 1:[1]
textAreaRef.current is possibly null. In fact, null is the default initial value you've set the textAreaRef to.
const textAreaRef = useRef(null);
What the warning is saying that textAreaRef.current is possibly null but you are accessing it in an unsafe way in order to invoke the select function.
You might be able to use the Optional Chaining operator (Typescript 3.7):
textAreaRef.current?.select();
Or you just use a null-check/guard-clause:
textAreaRef.current && textAreaRef.current.select();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Drew Reese |
