I am trying to filter A Flat List by using search.
I am using the Search Component & FlatList from react-native-elements
and react-native
.
The code listed below: I am trying to render the whole flatlist or render just the filtered flatlist from the users search text.
The code listed below:
this.state = {
cryptos: [],
refreshing: true,
filteredCryptos: [],
searchText: '',
};
<SearchBar
round={true}
lightTheme={true}
placeholder="Search ..."
placeholderTextColor="#000000"
autoCorrect={false}
autoCapitalize={false}
onChangeText={this.search}
value={this.state.searchText}
/>
<FlatList
data={
this.state.filteredCryptos && this.state.filteredCryptos.length > 0
? this.state.filteredCryptos
: this.state.cryptos
}
renderItem={({item}, index) =>
item !== null ? (
<CryptoItem
key={index}
crypto={item}
cryptoDisplay={item.DISPLAY.USD}
onClick={() => this.onClickSubscription()}
/>
) : (
<ActivityIndicator size="large" />
)
}
keyExtractor={item => item.CoinInfo.Id}
refreshing={this.state.refreshing}
onRefresh={this.handleRefresh.bind(this)}
/>
Search Function
search = searchText => {
this.setState({searchText: searchText});
let filteredCryptos = this.state.cryptos.filter(function (item) {
return item.CoinInfo.includes(searchText);
});
this.setState({filteredCryptos: filteredCryptos});
};
Data I am trying to match From the API is CoinInfo - FullName or Name
.
CoinInfo: {Id: '1182', Name: 'BTC', FullName: 'Bitcoin', Internal: 'BTC', ImageUrl: '/media/37746251/btc.png', …}
DISPLAY: {USD: {…}}
RAW: {USD: {…}}
CodePudding user response:
Convert both your search string and searching Object into lowercase string and perform this operation, it will work.
search = searchText => {
this.setState({searchText: searchText});
let filteredCryptos = this.state.cryptos.filter(function (item) {
let dataString = JSON.stringify(item.CoinInfo).toLowerCase();
let searchText = searchText.toLowerCase();
return dataString.includes(searchText);
});
this.setState({filteredCryptos: filteredCryptos});
};
CodePudding user response:
You would want to match the text in the FullName
or Name
properties in your search function.
search = searchText => {
this.setState({searchText: searchText});
// searchText empty, reset filtered array
if(!searchText){
this.setState({filteredCryptos: []});
return;
}
let filteredCryptos = this.state.cryptos.filter(function (item) {
// Defaults to empty string
let name = item.CoinInfo ? (item.CoinInfo.FullName || item.CoinInfo.Name || "") : "";
// If no such property, skip
if(!name) return false
// Change to both to lowercase, as you want to match 'bitcoin' and 'Bitcoin'
return name.toLowerCase().includes(searchText.toLowerCase());
});
this.setState({filteredCryptos: filteredCryptos});
};