by Sai gowtham

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.

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

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

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

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

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course