Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select all text in input with Reactjs, when it focused?

People also ask

How do you select input text in React?

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.

How do you select all text in input?

The HTMLInputElement. select() method selects all the text in a <textarea> element or in an <input> element that includes a text field.

How do you focus out from textbox in React JS?

To handle focus out in React, we use 'onFocusOut'. It is passed as an attribute in <input> elements, and can be used to perform actions when the cursor leaves the input box. React's onFocusOut event is related to the keyboard focus. When the focus is lost, the onFocusOut event is triggered.


Functional component:

const handleFocus = (event) => event.target.select();
const Input = (props) => <input type="text" value="Some something" onFocus={handleFocus} />

ES6 class component:

class Input extends React.Component {
    handleFocus = (event) => event.target.select();

    render() {
        return (
            <input type="text" value="Some something" onFocus={this.handleFocus} />
        );
    }
}

React.createClass:

React.createClass({
    handleFocus: function(event) {
      event.target.select();
    },

    render: function() {
      return (
        <input type="text" value="Some something" onFocus={this.handleFocus} />
      );
    },
})

Thanks, I appreciate it. I did it so:

var input = self.refs.value.getDOMNode();
            input.focus();
            input.setSelectionRange(0, input.value.length);

var InputBox = React.createClass({
  getInitialState(){
    return {
      text: ''
    };
  },
  render: function () {
    return (
      <input
        ref="input"
        className="mainInput"
        placeholder='Text'
        value={this.state.text}
        onChange={(e)=>{this.setState({text:e.target.value});}}
        onFocus={()=>{this.refs.input.select()}}
      />
    )
  }
});

You have to set ref on the input and when focused you have to use select().


Another Way Functional Component with useRefHook:

const inputEl = useRef(null);

function handleFocus() {
  inputEl.current.select();
}

<input
  type="number"
  value={quantity}
  ref={inputEl}
  onChange={e => setQuantityHandler(e.target.value)}
  onFocus={handleFocus}
/>

In my case I wanted to select the text from the beginning after the input appeared in the modal:

componentDidMount: function() {
    this.refs.copy.select();
},

<input ref='copy'