Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

102
Visualizações
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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

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();
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda