Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

105
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda