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:

Table of Contents

  1. onClick Hook
  2. onFocus Hook
  3. Using Reference

onClick Hook

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

App.js
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;

onFocus Hook

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

App.js
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;

Using Reference

The useRef hook helps us to access the dom nodes or html elements. Let’s see an example using useRef.

App.js
import React, { useRef } from "react";

function App() {
  const refName = useRef(null);

  const selectAllText = (e) => {
    refName.current.select();
  };

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

export default App;

That’s it. Thanks for reading.