Jagrati
Jagrati

Reputation: 12222

onFocus not getting cursor position with selectionStart

I am trying to get the caret position of where the user has clicked on a text box. I want to add a certain text at the position the user clicks the input. I am trying to do it in the onFocus method of the input. However, e.target.selectionStart gives me 0 always.

class Input extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: "hello"
    };
  }

  onFocus = e => {
    console.log(e.target.id);
    console.log(e.target.selectionStart); // receiving only 0 here
  };

  onChange = e => {
    this.setState({
      value: e.target.value
    });
  };

  render() {
    return (
      <input
        id="my-input"
        onChange={this.onChange}
        value={this.state.value}
        onFocus={this.onFocus}
      />
    );
  }
}

Any help is appreciated

CodeSandbox https://codesandbox.io/s/6x623x50r

Upvotes: 1

Views: 1771

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 282010

Instead of getting the cursor position value onFocus event, do it onMouseUp event. onFocus is not called when the input is focussed and you click somewhere else within the same input.

class Input extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: "hello"
    };
  }

  onMouseUp = e => {
    console.log(e.target.id);
    console.log(e.target.selectionStart);
  };

  onChange = e => {
    this.setState({
      value: e.target.value
    });
  };

  render() {
    return (
      <input
        id="my-input"
        onChange={this.onChange}
        value={this.state.value}
        onMouseUp={this.onMouseUp}
      />
    );
  }
}

Working codeSandbox

There is a bug getting selectionStart onFocus event, you can check the issue here

Upvotes: 1

Related Questions