Skip to content

Instantly share code, notes, and snippets.

@metehansenol
Last active February 10, 2024 22:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save metehansenol/46d065b132dd8916159910d5e9586058 to your computer and use it in GitHub Desktop.
Save metehansenol/46d065b132dd8916159910d5e9586058 to your computer and use it in GitHub Desktop.
In Memory search implementation with React Native FlatList and SearchBar
import React, {Component} from 'react';
import {StyleSheet, View, FlatList} from 'react-native';
import {SearchBar} from 'react-native-elements';
import ListItem from '../components/ListItem';
import Config from "../Config";
export default class DemandListScreen extends Component {
constructor(props) {
super(props);
this.state = {
searchText: "",
selectedId: -1,
data: [],
filteredData: []
};
}
async componentDidMount() {
let data = await fetch(`${Config.apiUrl}/items`)
.then(response => response.json());
this.setState({data: data});
}
search = (searchText) => {
this.setState({searchText: searchText});
let filteredData = this.state.data.filter(function (item) {
return item.aciklama.includes(searchText);
});
this.setState({filteredData: filteredData});
};
render() {
return (
<View style={styles.container}>
<SearchBar
round={true}
lightTheme={true}
placeholder="Search..."
autoCapitalize='none'
autoCorrect={false}
onChangeText={this.search}
value={this.state.searchText}
/>
<FlatList
data={this.state.filteredData && this.state.filteredData.length > 0 ? this.state.filteredData : this.state.data}
keyExtractor={(item) => `item-${item.id}`}
renderItem={({item}) => <ListItem
id={item.id}
code={item.code}
description={item.description}
/>}
ItemSeparatorComponent={() => <View style={styles.separator}/>}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1
},
separator: {
flex: 1,
height: StyleSheet.hairlineWidth,
backgroundColor: '#8E8E8E'
}
});
@DevAelius
Copy link

<FlatList
data={this.state.filteredData && this.state.filteredData.length > 0 ? this.state.filteredData : this.state.data}
/>

Got solution from above code, Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment