Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autoselect text in input - Reactjs

Tags:

reactjs

input

Is there way to select text to override immediately after render?? The select i mean - enter image description here

like image 928
Lukáš Unzeitig Avatar asked Mar 11 '23 05:03

Lukáš Unzeitig


1 Answers

You can try to use two methods .focus and .select

.focus() method sets focus on the specified element, if it can be focused.

.select() method selects all the text in a element or an element with a text field.

const App = React.createClass({
  getInitialState() {
    return { text: 'Default text' }
  },
	
  componentDidMount() {
    this.refs.input.focus();
  },
  
  handleChange(e) {
    this.setState({ text: e.target.value })
  },
   
  handleFocus(e) {
    e.currentTarget.select();
  }, 
  
  handleClick() {
    this.refs.input.focus();
  },

  render() {    
    return <div>
      <input 
        type="text" 
        ref="input"
        value={ this.state.text } 
        onChange={ this.handleChange }
        onFocus={ this.handleFocus }
      />
      <p>{ this.state.text }</p> 
      <button onClick={ this.handleClick }>Select Input Text</button>
    </div>;
  }
});


ReactDOM.render(
  <App />,
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>
like image 167
Oleksandr T. Avatar answered Mar 23 '23 21:03

Oleksandr T.