Author -  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>
  );
}

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY