0

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.

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
Leo Messi
  • 5,157
  • 14
  • 63
  • 125

1 Answers1

0

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();
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • I've tried with this method but I think that typescript doesn't let it work, do you know what type to assing to `e` from `copyToClipboard(e)`? And after adding `textAreaRef.current && textAreaRef.current.select();` is says `Property 'select' does not exist on type 'never'.ts(2339)` – Leo Messi Jan 26 '22 at 05:34
  • @LeoMessi Unfortunately, no, I'm minimally versed in Typescript. You might be able to declare it `any` until you can find a more accurate/restrictive type declaration. I think it'd be something like `HTMLInputElement` assuming `Input` is rendering an `input` tag and attaching the ref to it. – Drew Reese Jan 26 '22 at 05:45