Jimmy
Jimmy

Reputation: 3850

Cursor at the beginning of an autofocused textarea with React

I am using a text area with an autofocus on mount with React such that the cursor is placed at the very end of the text area. How do I get this cursor to be placed at the very beginning instead(see snippet below)? Thanks!

class App extends React.Component {
  componentDidMount() {
    this.textArea.focus();
  }
  
  render() {
    return (
      <textarea 
        ref={node => this.textArea = node}
        value="Hello, I want this cursor to be at the beginning (before the hello) when on focus, and not at the end."
      />
    );
  }
}

ReactDOM.render(<App />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="app"></div>

Upvotes: 2

Views: 2060

Answers (2)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195972

You could use the HTMLTextAreaElement.selectionEnd property and set it to 0 when the focus event triggers.

class App extends React.Component {

  handleFocus(e){
    const target = e.target;
    setTimeout(() => target.selectionEnd = 0,0);
  }
  
  render() {
    return (
      <textarea 
        onFocus={this.handleFocus} 
        value="Hello, I want this cursor to be at the beginning (before the hello) when on focus, and not at the end."
      />
    );
  }
}

ReactDOM.render(<App />, document.getElementById('app'));
<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>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="app"></div>


Updated answer and added a setTimeout because chrome would mess up when focusing with a mouse

Upvotes: 2

Jimmy
Jimmy

Reputation: 3850

Here is the answer, thanks to Gabriele Petrioli:

class App extends React.Component {
  componentDidMount() {
    this.textArea.selectionEnd=0;
    this.textArea.focus();
  }
  
  render() {
    return (
      <textarea 
        ref={node => this.textArea = node}
        value="Hello, I want this cursor to be at the beginning (before the hello) when on focus, and not at the end."
      />
    );
  }
}

ReactDOM.render(<App />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="app"></div>

Upvotes: 0

Related Questions