Clearing inputText using react-bootstrap-typeahead when invalid data is entered
Asked Answered
P

2

5

I'm trying to validate a selection using react-bootstrap-typeahead and clear out the input text if invalid when I move to another area of the page.

I can't figure out a good way to do this.

The onBlur for the Typeahead component doesn't fire at the right time to validate and clear.

Any suggestions would be appreciated

Here is my typeahead definition

        <Typeahead  bsSize="sm"
                    defaultSelected = {this.props.options.slice(selectedIndex)}
                    clearButton
                    labelKey="roomNumber"
                    options={this.props.options}
                    placeholder={this.props.placeholder}                          
                    name={this.props.nameId}
                    ref={ref => this.roomChoice = ref}
                    onChange={this.onChangeHandler.bind(this)}
                    onInputChange={this.onInputChangeHandler.bind(this)}
                    onBlur={this.onBlurHandler.bind(this)} 
                    onFocus={this.onFocusHandler.bind(this)} 
                  />

Here is my onBlur Function:

onBlurHandler(event)
{   
         if (this.roomInputText)
        {
            if (!this.roomSelectedOption)
            {
                this.roomChoice.getInstance().clear()
            }
        }

}

The onBlur isn't firing in the right time for me to have a selected option if someone entered text.

Pearlypearman answered 31/8, 2017 at 18:3 Comment(0)
G
6

Get the ref in TypeAhead instance, using a callback ref, and use in onchange event call.

<div>
  <Typeahead
    options={[...]}
    ref={(ref) => this._typeahead = ref}
    onInputChange={this.onInputChangeSelection}
 />
</div>




onInputChangePartsSelection = (value) => {
    if (value) {
    const instance = this._typeahead.getInstance()
    instance.clear()
    instance.focus()
    }
  }
Graham answered 21/4, 2019 at 9:1 Comment(2)
Thanks! I now understand that the actual behavior is different from the documentation: ericgio.github.io/react-bootstrap-typeahead/#public-methods, which suggests this._typeahead.clear() would work.Marietta
The API has changed tp ref.current.focus() and if you're getting this is not a function error then probably need upgrade the package github.com/ericgio/react-bootstrap-typeahead/issues/631Bea
C
0

I was using AsyncTypeAhead and had to do the following.

var asyncTypeAhead = typeAhead as AsyncTypeahead;
asyncTypeAhead.getInstance().clear();

I found this post useful https://github.com/ericgio/react-bootstrap-typeahead/issues/359

Conduit answered 10/2, 2020 at 5:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.