Selecting all text in the input field with React
In this tutorial, we are going to learn about how to select all text in a form input field when a button is clicked in the React app.
Selecting all text
To select the all text in an input field, we can use the e.target.select()
method in react.
Here is an example of a functional react component, that selects the text by clicking on the input field.
import React from "react";
export default function App() {
const handleClick = (e) => {
e.target.select(); };
return (
<div className="App">
<input type="text" onClick={handleClick} value="King" /> </div>
);
}
Example for class component:
import React,{Component} from "react";
class App extends Component {
handleClick = (e) => {
e.target.select(); };
render() {
return (
<div className="App">
<input type="text" onClick={this.handleClick} value="King" /> </div>
);
}
}
export default App;
Here we using the useRef hook to get the reference of a input field and selects the text using current.select()
method.
import React, { useRef } from "react";
export default function App() {
const inputRef = useRef(null);
const handleClick = () => {
inputRef.current.select(); };
return (
<div className="App">
<input ref={inputRef} onClick={handleClick} value="King" /> </div>
);
}
Similarly, we can also select the text by focussing on an input field like this.
import React from "react";
export default function App() {
const handleFocus = (e) => {
e.target.select(); };
return (
<div className="App">
<input type="text" onFocus={handleFocus} value="King" /> </div>
);
}