How to select all text content of input textarea in ReactJS

Today, I am explaining you, how to select all text content of input textarea in ReactJS. if you are working in ReactJS so this post in very useful to you. I will show you through some events like onClick, onFocus and useRef hook. I am explaining you three ways with use of e.target.select() method.

Table of Contents –

  1. onFocus
  2. onClick
  3. Using Reference Hook

1. onFocus

The onfocus event will occurs when any HTML element gets focus.

Example :

import React, { useRef } from "react";

function Unity() {

   const textAreaContentFocus = (e) => {
    e.target.select();//onFocus function select all text in textarea
  };
  

  return (<><div id="wrapper" className="full-screen" style={{ background: "#ccc"}} >
  	<textarea onFocus={textAreaContentFocus}>
        Hi, Wel come to Web Developers India websites ReactJS post. onFocus function select all text.
      </textarea><br/></div> </>

  );
}

export default Unity;

Output :

2. onClick

The onClick event will occurs when call a function and perform an action when an element is clicked.

Example :

import React, { useRef } from "react";

function Unity() {

   const textAreaContentClick = (e) => {
    e.target.select();//onClick function select all text in textarea
  };
  

  return (<><div id="wrapper" className="full-screen" style={{ background: "#ccc"}} >
  <textarea onClick={textAreaContentClick}>
        Hi, Wel come to Web Developers India websites ReactJS post. onClick function select all text.
      </textarea><br/></div> </>

  );
}

export default Unity;

Output :

3. Using Reference Hook

Using The useRef hook, it help us to access the html elements.

Example :

import React, { useRef } from "react";

function Unity() {

  const refNameContent = useRef(null);
  const textAreaContentRefClick = (e) => {
    refNameContent.current.select();
  };
  

  return (<><div id="wrapper" className="full-screen" style={{ background: "#ccc"}} >
   <textarea ref={refNameContent} onClick={textAreaContentRefClick}>
        Hi, Wel come to Web Developers India websites ReactJS post. onClick Ref function select all text.
      </textarea><br/></div> </>

  );
}

export default Unity;

Output :

Leave a Reply

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

+ 20 = 27