Autosuggest on input of specific character with ReactJS

All we need is an easy explanation of the problem, so here it is.

So when using facebook if you enter an @symbol it knows you want to link to a friend/page. Im putting together a UI that allows users to mark up text from ancient documents. What I would like to do is if a user highlights a word or puts an @ # ~ £ symbol before a word it pops up an autosuggest or options dropdown. So if I typed ‘This is a document related to @name’ when I typed @name it suggests names, or places etc, in fact I will need it to open another modal so you can enter more information about that user/place/item.

Im wondering if this is something that can be achieved with ReactJS from the documentation I cant seem to find this functionality out of the box, any pointers greatfully received.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Of course this is possible.
I won’t use the actual syntax, but I’ll point you in the right direction.

Say you have your search/input component.

It’s render function will look something like:

render: function(){
    return (<div>
            <input onChange={this.onChange}></input>
            <SuggestionsList data={this.state.value} show={this.state.autoSuggest}></SuggestionsList>
           <div>);
}

Now let’s create the onChange function to set the state to show the autoSuggest when we want it to:

onChange: function(val){
    var state = {value: val};
    if(val[0] === '@'){
       state.autoSuggest=true;
    }
    this.setState(state);
}

All you need to do now is create the SuggestionsList component which will handle getting the suggestions and returning the list.

Note that you don’t need to use this exact pattern, it may be more correct not to return the suggestionslist at all if you don’t want to show any suggestions, but this is up to you.

I suggest you follow facebook’s comments tutorial here: http://facebook.github.io/react/docs/tutorial.html

Where they dynamically get comments from the server and update. It’s essentially the same pattern.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply