I would like to display data from Firebase in Listview in React Native.
I succeed to display static data like "hey", but I don't know how I can display Firebase data. My database is like that : users > email (for example in order to display email).
I did firebaseConfig and two .js files :
Code :
import React, { Component } from 'react';
import { AppRegistry, View, ListView, StyleSheet, Text } from 'react-native';
import Row from './Row';
import * as firebase from 'firebase';
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: 20,
},
separator: {
flex: 1,
height: StyleSheet.hairlineWidth,
backgroundColor: '#8E8E8E',
},
});
// Initialize Firebase
const firebaseConfig = {
apiKey: "xx",
authDomain: "xx",
databaseURL: "xx",
storageBucket: "<your-storage-bucket>",
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
export default class App extends Component {
constructor(props) {
super(props);
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
dataSource: ds.cloneWithRows(['row 1', 'row 2']),
};
}
render() {
return (
<ListView
style={styles.container}
dataSource={this.state.dataSource}
renderRow={(data) => <Row {...data} />}
renderSeparator={(sectionId, rowId) => <View key={rowId} style={styles.separator} />}
/>
);
}
}
AppRegistry.registerComponent('App', () => App);
Code :
import React from 'react';
import { View, Text, StyleSheet, Image } from 'react-native';
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 12,
flexDirection: 'row',
alignItems: 'center',
},
text: {
marginLeft: 12,
fontSize: 16,
},
});
const Row = (props) => (
<View style={styles.container}>
<Text style={styles.text}>
"Hey"
</Text>
</View>
);
export default Row;
First, you need to fetch/query firebase for your data. This is typically done in the constructor or componentWillMount
lifecycle method.
Something along the lines of:
firebaseApp.database().ref().child(`${<someUserPath>}/username`).once("value", (snapshot) => {
this.setState({ username: snapshot.val() });
});
After you have your desired data, you then pass it down to the ListView
as props like this:
<ListView
dataSource={this.state.dataSource.cloneWithRows([this.state.username])} />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.