1

I'm trying to implement a search filter in reactjs, I've tried bind method to `onChange´ event but it triggered for every single letter. How can it make it work to after type 3 letters.

    

     var FilteredList = React.createClass({
      filterList: function(event){
        var updatedList = this.state.initialItems;
        updatedList = updatedList.filter(function(item){
          return item.toLowerCase().search(
            event.target.value.toLowerCase()) !== -1;
        });
        this.setState({items: updatedList});
      },
      getInitialState: function(){
         return {
           initialItems: [
             "Apples",
             "Broccoli",
             "Chicken",
             "Duck",
             "Eggs",
             "Fish",
             "Granola",
             "Hash Browns"
           ],
           items: []
         }
      },
      componentWillMount: function(){
        this.setState({items: this.state.initialItems})
      },
      render: function(){
        return (
          <div className="filter-list">
            <form>
            <fieldset className="form-group">
            <input type="text" className="form-control form-control-lg" placeholder="Search" onChange={this.filterList}/>
            </fieldset>
            </form>
          <List items={this.state.items}/>
          </div>
        );
      }
    });
    
    var List = React.createClass({
      render: function(){
        return (
          <ul className="list-group">
          {
            this.props.items.map(function(item) {
              return <li className="list-group-item" data-category={item} key={item}>{item}</li>
            })
           }
          </ul>
        )  
      }
    });
    
    React.render(<FilteredList/>, document.getElementById('app'));

https://codepen.io/mtclmn/pen/QyPVJp, i tried to change this code for my case but im stuck with triggering it after 3 letters scenario.

Any idea would be much appreciate.

3
  • Please share what you have already tried. Perhaps something as simple as not triggering the search function until 3 characters are on the input box would be a simple trick to achieve the same. Commented Dec 21, 2020 at 6:26
  • Please visit help center, take tour to see what and How to Ask. Do some research, search for related topics on SO; if you get stuck, post a minimal reproducible example of your attempt, noting input and expected output, preferably in a Stacksnippet Commented Dec 21, 2020 at 6:28
  • @Samridh Tuladhr, code example added Commented Dec 21, 2020 at 6:36

3 Answers 3

1

onChange is triggered whenever the event happened. So when even.target.value as values input tag is changed then function is activated. Unlike Other methods like onClick or onSubmit that is activated after clicking or clicking the submit button, every change is detected by onChange event. That's how different between onChange and onClick. If you want to search after typing 3 letters then there is an easy one approach. Setting condition value.length >= 3 would be helpful.

https://codepen.io/jacobkim9881/pen/LYRjLwd

Sign up to request clarification or add additional context in comments.

2 Comments

Even thought it seems straight forward, but once the user clears the field, We must get back the original list of select items which is not happening here :) in your code yet codepen.io/jacobkim9881/pen/LYRjLwd
As @Imran Rafiq Rather who is a nice React dev kindly cleared above, the demonstration is above :)
1

As the function which is pass to the onChange property of an input field is called any time you type on the keyboard. You can check inside of that function before performing any change which you need as updating the state If the value of event.target.value length is greather or equal to 3 like this

filterList: function(event){
    if(event.target.value.length >= 3) {
       // Here you can perform what you need
    }   
}

Comments

1

Modified your filterList function to only start the searching when there are 3 characters available, otherwise, return the initialItems list :

filterList: function(event){
    if(event.target.value.length > 2){
    var updatedList = this.state.initialItems;
    updatedList = updatedList.filter(function(item){
      return item.toLowerCase().search(
        event.target.value.toLowerCase()) !== -1;
    });
    this.setState({items: updatedList});
    }
    else{
      console.log(this.state.initialItems)
      this.setState({items: this.state.initialItems})
    }
  }

Edit: the previous answer posted here, is doing the same as me. I have added an additional else condition to return the entire list when there is nothing on the search bar. Please change it to else if to suit your requirements.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.