How to Select all Text of Textarea in React

Published on September 23, 2020 45 sec read

HIRE US 🖐
We're available to do freelance project. Take a look at our services!

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. 🙂

Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.

Follow

Leave a Reply

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