Reputation: 331
I want to learn to use FlatList in react native,but I can't figure how to push elements in data (the FlatList array). Can someone help me ?
Here's my react native code:
import React, { Component } from 'react';
import { FlatList, StyleSheet, Text, Button,View ,TextInput} from 'react-native';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {text: '',
data:[]
};
}
render() {
return (
<View>
<TextInput
style={{height: 40}}
placeholder="Task"
onChangeText={(text) => this.setState({text})}/>
<Button title="Add" onPress={this.addTask} />
<FlatList
renderItem={({item}) => <Text style={styles.item}>{item.key}</Text>}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: 22
},
item: {
padding: 10,
fontSize: 18,
height: 44,
}
});
Upvotes: 0
Views: 2257
Reputation: 267
You need to add data prop in the Flatlist Component.
<FlatList
data={[{key: 'a'}, {key: 'b'}]}
renderItem={({item}) => <Text>{item.key}</Text>}
/>
the renderItem is basically looping over elements in the data array. It cannot do that if there is no data. If you are starting with empty data just use data={[]}
Upvotes: 2