javascriptreactjsmaterial-uimui-autocomplete

React - Material UI Autocomplete on words that aren't the first in a sentence


I am trying to implement autocomplete on hashtags for my webapp, so typing #h would bring up a menu with #hello, #hope, etc etc. As im using Material UI everywhere else it would be great if i could just use the autocomplete-component, but it only works on the first word typed in the AutoComplete-box. In other words, it can autocomplete "#Hello what a great day", but if i type more than one word the autocomplete is disabled, so "It sure is a great day #Hello" won't auto complete the #Hello. None of their examples can do this either. Does anyone have any pointers?


Solution

  • Here is how you can do it with the material-ui components:

    <div style={{position:'relative'}}>
    
          <AutoComplete
            hintText="Type anything"
            dataSource={['#hello','#how','#are','#you']}
            ref={ref=>this.autocompleteRef=ref}
            searchText={this.state.searchText}
            onNewRequest={this.onNewRequest}
            textFieldStyle={{visibility:'hidden'}}
            style={{position:'absolute',top:'0',left:'0'}}
          />
          <TextField
            value={this.state.fullText || ''}
            hintText="fullText"
            onChange={this.myTextChange}
            type="text"
          />
        </div>
    

    And the functions should look something like:

    myTextChange=(event)=>{
      let fullText = event.target.value,searchText;
      let hashTaggingIndex = this.hashTaggingIndex;
      if(hashTaggingIndex && hashTaggingIndex>-1){
        if(fullText[fullText.length-1]===' ') this.hashTaggingIndex = -1;
        else {
          searchText = fullText.substring(hashTaggingIndex+1,fullText.length);
        }
      } else if(fullText[fullText.length-1]==='#') { 
         this.hashTaggingIndex=fullText.length-1;
      }
      this.setState({fullText,searchText});
      if(this.autocompleteRef && hashTaggingIndex && hashTaggingIndex>-1){
        this.autocompleteRef.handleChange(event);
       }
    };
    
    onNewRequest=(value)=>{
      let fullText=this.state.fullText;
      fullText = fullText.substring(0,this.hashTaggingIndex) + value;
      this.setState({fullText})
    };
    

    Have fun:)