Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

107
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!