2

Supposing you have an array of 10 items in react native and you only want to display just 5 on a screen.

DATA

state = {
      people: [
       {firstName: Ben, lastName: Mark},
       {firstName: Linda, lastName: Hanson},
       {firstName: Arthur, lastName: Merlin},
       {firstName: Jesus, lastName: Joshua}
]
}

VIEW

<ScrollView >
      {
        people.map((item, i) => {
      return (
      <View key={i} style={styles.user}>
      <Card >
       <ListItem
        hideChevron={true}
        title={item.firstName} {item.lastName}
        />
        </Card>
      </View>
          );
        })
      }
    </ScrollView>

Please how can i achieve this?

1
  • 3
    That depends, do you want to show the first 5, the last 5, random 5 etc. Your question needs to be a bit clearer, what have you tried so far? The array you've given us only contains four. Your map code looks fine, so perhaps write another function which takes this.state.people, get's 5 people, then update the state with this.setState({fivePeople: value}); and then map over that array instead? Commented Jan 29, 2019 at 10:45

2 Answers 2

4

Simple, just use slice on your array :

people.slice(0, 5).map((item, i)

It will only take the first 5 values of your array.

Sign up to request clarification or add additional context in comments.

Comments

3

You can slice your data

<ScrollView >
  {
    people.slice(0, 5).map((item, i) => {
  return (
  <View key={i} style={styles.user}>
  <Card >
   <ListItem
    hideChevron={true}
    title={item.firstName} {item.lastName}
    />
    </Card>
  </View>
      );
    })
  }
</ScrollView>

2 Comments

See @Treycos answer, try to edit/expand on that rather than making a duplicate answer.
sorry but it was not displayed when i had answered. its just 10 to 20 sec diff

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.