Nick Wild
Nick Wild

Reputation: 575

React-Bootstrap-Typeahead allowNew select-on-blur

Is it possible to configure this so when allowNew is set that any new entry in this field would be selected on blur rather than clicking on the new item "menu"

EDITED: This is my existing child component

<Typeahead
   labelKey="label"
   allowNew
   selectHintOnEnter
   options={props.campaignOptions}
   placeholder="Campaign Name..."
   onChange={props.campaignName}
 />

And this is my parent component...

campaignName (campaign){
  campaign.length ? this.setState({campaignSelected:campaign}) : this.setState({campaignSelected:''})
  }

...

<FormGroup>
    <Campaign
     campaignName={this.campaignName.bind(this)}
     campaignOptions={[...new Set(this.props.records.map(options => options.campaign))]}/>
 </FormGroup>

Upvotes: 3

Views: 3266

Answers (2)

Nick Wild
Nick Wild

Reputation: 575

Thanks for the advice, but I managed to get this to work with a much simpler approach that means that I don't need to use onBlur and I just store the onInputChange in the state in the parent.

  const {campaignOptions, campaignValue, campaignName} = this.props;

  ...

<Typeahead
    labelKey="label"
      allowNew
      placeholder="Campaign Name..."
      onInputChange={campaignName}
      options={campaignOptions}
      selected={campaignValue}
/>

Upvotes: 0

ericgio
ericgio

Reputation: 3509

It's possible in the single-select case. Here's how you could do it:

class MyComponent extends React.Component {
  state = {
    selected: [],
    text: '',
  };

  render() {
    const {selected, text} = this.state;

    return (
      <Typeahead
        allowNew
        onBlur={(e) => this.setState({selected: text ? [text] : []})}
        onChange={selected => this.setState({selected})}
        onInputChange={(text) => this.setState({text})}
        options={this.props.options}
        selected={selected}
      />
    );
  }
}

Note that the code above simply sets the input value as the selection. You most likely want to convert the string to an object that has a unique identifier, like an ID.

It's not possible to do it in the multi-select case because you'd need to clear just the text input (not the selections) after the selecting the text, and there's no API for doing that.

Upvotes: 2

Related Questions