Search Filter with React Native on FlatList

前端 未结 10 1240
孤街浪徒
孤街浪徒 2020-12-28 08:33

I am trying to search through a flatlist based on a search bar text. The problem I am running into is that when the user mistypes...say they wanted to type \"burger\" but ty

10条回答
  •  鱼传尺愫
    2020-12-28 09:00

    For a useful in-memory search you should keep initial data seperately.

    I have more simple solution for this.

    This solution for in-memory search on FlatList's data and uses it String.prototype​.includes() method to search substring.

    You can find full source code of this component in this gist; https://gist.github.com/metehansenol/46d065b132dd8916159910d5e9586058

    My initial state;

    this.state = {
      searchText: "",
      data: [],
      filteredData: []
    };
    

    My SearchBar component (it comes from react-native-elements package);

    
    

    My search method;

    search = (searchText) => {
      this.setState({searchText: searchText});
    
      let filteredData = this.state.data.filter(function (item) {
        return item.description.includes(searchText);
      });
    
      this.setState({filteredData: filteredData});
    };
    

    And last my FlatList's DataSource expression;

     0 ? this.state.filteredData : this.state.data}
      keyExtractor={(item) => `item-${item.id}`}
      renderItem={({item}) => }
    />
    

    Happy coding...

提交回复
热议问题