Skip to content

Instantly share code, notes, and snippets.

@tonysherbondy
Created July 24, 2016 03:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonysherbondy/27c3b07e6ea4d9f91f6ac2421a6e8785 to your computer and use it in GitHub Desktop.
Save tonysherbondy/27c3b07e6ea4d9f91f6ac2421a6e8785 to your computer and use it in GitHub Desktop.
Final implementation of simple Search Bar for React Native
import React from 'react'
import {
View,
ListView,
Text,
StyleSheet,
TextInput,
} from 'react-native'
import names from './names'
const styles = StyleSheet.create({
container: {
flex: 1,
},
navbar: {
padding: 5,
height: 50,
justifyContent: 'flex-end',
alignItems: 'center',
backgroundColor: 'rgb(222, 222, 222)',
},
navbarText: {
fontWeight: 'bold',
fontSize: 20,
},
list: {
},
row: {
padding: 10,
height: 50,
borderBottomColor: 'gray',
borderBottomWidth: StyleSheet.hairlineWidth,
},
searchBar: {
backgroundColor: 'rgb(126, 126, 126)',
},
searchInput: {
height: 30,
margin: 5,
paddingLeft: 10,
backgroundColor: 'white',
borderRadius: 5,
},
})
class SearchBar extends React.Component {
state = {
dataSource: new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2,
}),
searchText: null,
}
getFilteredData() {
const { dataSource, searchText } = this.state
if (searchText === null || searchText.length === 0) {
return dataSource.cloneWithRows(names)
}
const matches = names.filter(name => name.search(searchText) >= 0)
return dataSource.cloneWithRows(matches)
}
render() {
const renderRow = row => (
<View style={styles.row}>
<Text>{row}</Text>
</View>
)
return (
<View style={styles.container}>
<View style={styles.navbar}>
<Text style={styles.navbarText}>Top Passwords</Text>
</View>
<View style={styles.searchBar}>
<TextInput
style={styles.searchInput}
value={this.state.searchText}
autoCapitalize="none"
onChangeText={searchText => this.setState({ searchText })}
placeholder="Search"
/>
</View>
<ListView
style={styles.list}
dataSource={this.getFilteredData()}
renderRow={renderRow}
/>
</View>
)
}
}
export default SearchBar
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment