How to Select all Text of Textarea in React

We can select all content of an input field or textarea in many ways. I’m going to share three ways here. I’ll use e.target.select() method. Let’s start:

The onClick handler allows us to call a function and perform an action when an element is clicked.

import React from 'react';

function App() {
  const selectAllText = (e) => {
    e.target.select();
  };

  return(
    <div>
      <textarea onClick={selectAllText}>
        Text goes here
      </textarea>
    </div>
  )
}

export default App;

The onfocus event occurs when an element gets focus. Have a look at the example:

import React from 'react';

function App() {
  const selectAllText = (e) => {
    e.target.select();
  };

  return(
    <div>
      <textarea onFocus={selectAllText}>
        Text goes here
      </textarea>
    </div>
  )
}

export default App;

Leave a comment

Your email address will not be published. Required fields are marked *