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
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.
Md Obydullah
Software Engineer | Ethical Hacker & Cybersecurity...
Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.