Reputation: 689
I want to render only 3 of my items inside a FlatList
. Latter when I click the text new item will be rendered.
here is the example code:
export default class FlatListBasics extends Component {
renderNewItem = () => {
// do something here
}
render() {
return (
<View style={styles.container}>
<FlatList
data={[
{key: 'Devin'},
{key: 'Jackson'},
{key: 'James'},
{key: 'Joel'},
{key: 'John'},
{key: 'Jillian'},
{key: 'Jimmy'},
{key: 'Julie'},
]}
renderItem={({item}) => <Text onPress={this.renderNewItem}>{item.key}</Text>}
/>
</View>
);
}
So how I can achieve this? }
Upvotes: 2
Views: 8504
Reputation: 24660
You can use Array.prototype.slice()
to control amount of the data rendered. Set a count in your state and then add 1 to it every time you pressed the button. This way you are not dependent on how do you load your data. You can either use a local data source or a remote one with an API. Another key point is to add a keyExtractor
so the re-render will be more performance.
Example
const data = [
{key: 'Devin'},
{key: 'Jackson'},
{key: 'James'},
{key: 'Joel'},
{key: 'John'},
{key: 'Jillian'},
{key: 'Jimmy'},
{key: 'Julie'},
];
class FlatListBasics extends Component {
constructor(props) {
super(props);
this.state = {
itemsCount: 3
};
}
renderNewItem = () => {
if (this.state.itemsCount < data.length) {
this.setState((prevState) => ({ itemsCount: (prevState.itemsCount + 1) }));
}
}
render() {
return (
<View style={styles.container}>
<FlatList
data={data.slice(0, this.state.itemsCount)}
keyExtractor={(item, index) => item.key;}
renderItem={({ item }) => <Text onPress={this.renderNewItem}>{item.key}</Text>}
/>
</View>
);
}
}
Upvotes: 9
Reputation: 9407
So first prepare your 3 items data in your constructor:
let state = {
data = [{key: "Devin"}, {key: "Jackson"}, {key: "James"}]
}
And render your FlatList
.
Then, in renderItem
, you would have an onPress
that will add an item to your data
renderItem = () => {
<TouchableOpacity onPress=() => { this.setState({data: this.state.data.pushBack(/*your new item here*/)}) }
</TouchableOpacity>
}
this.setState
will force everything to rerender, therefore it will show the new added item.
Upvotes: 1