Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-native limit List items

i am using Flatlist from react-native and ListItem from react-native-elements,

i want to initially limit the number of list-items that are loaded on the screen.Otherwise it loads all the items that i have initially .

Suppose i have 300 list items but initially i only want to load 10 items ,instead of 300.

MY CODE:

import React, { Component } from 'react'
import {
   FlatList
} from 'react-native'

import {Avatar,Tile,ListItem} from 'react-native-elements'

export default class Login extends Component{
constructor(props) {
    super(props);


this.state = {
  data:[],
   dataSource: []

    };
  }


renderList(item,i){


  return(

<View>
<ListItem

subtitle={
<Avatar
  small
  rounded
  source={{uri: "https://s3.amazonaws.com/uifaces/faces/twitter/ladylexy/128.jpg"}}

/>
{<Text>{item.body}</Text>}
}

/>
<View>
    )
}

render(){  
    return( 
        <View>
<List>
<FlatList
        data={this.state.data}
        keyExtractor={item => item.id}
        renderItem ={({item,index}) => this.renderList(item,index)}
      />
</List>  
</View>
      )
  }
}
like image 832
Vish_TS Avatar asked Jul 26 '17 09:07

Vish_TS


Video Answer


1 Answers

Basically, what you need is to implement sort of pagination. You can do it by using onEndReached and onEndReachedThreshold(for more details look here) of FlatList to load more data when user reaches the end of list.

You can change your code like so:

import React, { Component } from 'react';
import { FlatList } from 'react-native';

import { Avatar, Tile, ListItem } from 'react-native-elements';

const initialData = [0,...,299]; //all 300. Usually you receive this from server or is stored as one batch somewhere
const ITEMS_PER_PAGE = 10; // what is the batch size you want to load.
export default class Login extends Component {
  constructor(props) {
    super(props);

    this.state = {
      data: [0,..., 9], // you can do something like initialData.slice(0, 10) to populate from initialData.
      dataSource: [],
      page: 1,
    };
  }

  renderList(item, i) {
    return (
      <View>
        <ListItem />
      </View>
    );
  }

  loadMore() {
    const { page, data } = this.state;
    const start = page*ITEMS_PER_PAGE;
    const end = (page+1)*ITEMS_PER_PAGE-1;

    const newData = initialData.slice(start, end); // here, we will receive next batch of the items
    this.setState({data: [...data, ...newData]}); // here we are appending new batch to existing batch
  }


  render() {
    return (
      <View>
        <FlatList
          data={this.state.data}
          keyExtractor={item => item.id}
          renderItem={({ item, index }) => this.renderList(item, index)}
          onEndReached={this.loadMore}
        />
      </View>
    );
  }
}
like image 126
magneticz Avatar answered Oct 12 '22 03:10

magneticz