Skip to content

Instantly share code, notes, and snippets.

@dacre-denny
Created December 27, 2018 20:02
Show Gist options
  • Save dacre-denny/dcd97e5a16e4c199d590f2ec096b5f7f to your computer and use it in GitHub Desktop.
Save dacre-denny/dcd97e5a16e4c199d590f2ec096b5f7f to your computer and use it in GitHub Desktop.
Example of <SectionList /> usage for React-Native
import * as React from 'react';
import { Text, View, StyleSheet, FlatList, ActivityIndicator,SectionList } from 'react-native';
import { Constants } from 'expo';
export default class Test extends React.Component {
constructor(props){
super(props);
this.state ={ isLoading: true, dataSource : []}
}
componentDidMount(){
return fetch('https://randomuser.me/api/?results=5')
.then((response) => response.json())
.then((responseJson) => {
let dataSource = responseJson.results.reduce(function(sections, item) {
let section = sections.find(section => section.gender === item.gender);
if(!section) {
section = { gender : item.gender, data : [] };
sections.push(section);
}
section.data.push(item);
return sections;
}, []);
this.setState({
isLoading: false,
dataSource: dataSource,
} );
})
.catch((error) =>{
console.error(error);
});
}
render() {
if(this.state.isLoading){
return(
<View style={{flex: 1, padding: 20}}>
<ActivityIndicator/>
</View>
)
}
return (<View style={{flex: 1, paddingTop:20}}>
<SectionList
renderItem={({item, index, section}) => <Text key={index}>{item.name.first},{ item.gender }</Text>}
renderSectionHeader={({section: {gender}}) => (
<Text style={{ fontWeight : 'bold' }}>{gender}</Text>
)}
sections={this.state.dataSource}
keyExtractor={(item, index) => item.login.uuid + index}
/>
</View>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment