fmoo / react-typeahead

Pure react-based typeahead and typeahead-tokenizer
ISC License
677 stars 231 forks source link

Reset or change Typeahead Value. #143

Open ritesh8467 opened 8 years ago

ritesh8467 commented 8 years ago

Is there any callback where i can change the Input value of Typeahead?

Case: These is a search bar and a reset button. I want to reset the value of search bar on clicking reset button. So how can i approach this case.

lipenco commented 8 years ago

:+1:

lgiraudel commented 8 years ago

You can force the state of the Typeahead:

this.refs.myInput.setState({
  entryValue: '',
  selection: null,
  selectionIndex: null,
  visible: []
});
cganas commented 8 years ago

:+1:

barbalex commented 8 years ago

nice. Would be worth mentioning in the readme

reason-bv commented 8 years ago

I went with replacing this method with a one-line change so that it definitely always pays attention to value when value is reset:

    typeahead.componentWillReceiveProps = function(nextProps) {
      this.setState({
        // Added this line.
        entryValue: nextProps.value,
        visible: this.getOptionsForValue(this.state.entryValue, nextProps.options)
      });
    };

You can do this with refs in the component including the typeahead. Somewhere in render():

<Typeahead
  // .. other props here ..
  value={ ... whatever value is tracked by here ... }

  ref={
    // Need to obtain a ref to this because it isn't behaving
    // completely correctly. We adjust things in
    // componentDidMount.
    (ref) => this._typeahead = ref
  }
/>

Then in componentDidMount():

componentDidMount () {
    this._typeahead.componentWillReceiveProps = function(nextProps) {
      this.setState({
        entryValue: nextProps.value,
        visible: this.getOptionsForValue(this.state.entryValue, nextProps.options)
      });
    };
  };
birge commented 8 years ago

Note that in the source code it says that entryValue should change name in the future and your code will explode :bomb: