0

I need all text inside react-bootstrap-typeahead to be selected when input is focused e.g. on click.

In public API there are no mentions about this.

How can I achieve this?

zmii
  • 4,123
  • 3
  • 40
  • 64

1 Answers1

1

There's no public API or canonical way to do it, but it's certainly possible. What you need to do is get the input node and then set the selection range. Here's an example:

class MyTypeahead extends React.Component {    
  render() {
    return (
      <Typeahead
        onFocus={(event) => {
          const inputNode = document.getElementById('typeahead-input');
          inputNode.setSelectionRange(0, inputNode.value.length);
        }}
        inputProps={{id: 'typeahead-input'}}
      />
    );
  }
}

EDIT: Alternate ways of getting the input node:

From the event:

class MyTypeahead extends React.Component {    
  render() {
    return (
      <Typeahead
        onFocus={(event) => {
          const inputNode = event.target;
          inputNode.setSelectionRange(0, inputNode.value.length);
        }}
        ...
      />
    );
  }
}

Using a ref:

class MyTypeahead extends React.Component {    
  render() {
    return (
      <Typeahead
        onFocus={(event) => {
          const inputNode = this.typeahead.getInstance().getInput();
          inputNode.setSelectionRange(0, inputNode.value.length);
        }}
        ref={(el) => this.typeahead = el}
        ...
      />
    );
  }
}
ericgio
  • 3,094
  • 4
  • 25
  • 44
  • Thanks. Just wondering - is there a way to identify focused node from the event somehow? Which would mean, there is no need to specify the id? Would be helpful when adding this behaviour to multiple typeaheads in one formgroup. – johnnyB Apr 27 '18 at 08:52
  • 1
    @johnnyB: yes, you can use `event.target`. See updated answer. – ericgio Apr 28 '18 at 21:04