Last active
February 10, 2024 22:08
-
-
Save metehansenol/46d065b132dd8916159910d5e9586058 to your computer and use it in GitHub Desktop.
In Memory search implementation with React Native FlatList and SearchBar
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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' | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
<FlatList
data={this.state.filteredData && this.state.filteredData.length > 0 ? this.state.filteredData : this.state.data}
/>
Got solution from above code, Thank you