简体   繁体   中英

How to create dynamic search filter in react JS?

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.

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
    }   
}

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM