Home > Software engineering >  How to get first element in array in React Native
How to get first element in array in React Native

Time:12-28

I tried to get only first element [0] of array and print in UI. I will get only first lesson in the array and then print.

{route.params.Lessons.map((lessons) => {
              return (
                <View>
                  <Text style={styles.lessonTitle}>Lesson 1</Text>
                  <Text style={styles.lessonDescription}>{lessons.lessonName}</Text>
                </View>
              )
            })}

enter image description here

Thanks

CodePudding user response:

You could use something like this code:

<View>
  <Text style={styles.lessonTitle}>Lesson 1</Text>
  <Text style={styles.lessonDescription}>{route.params.Lessons[0].lessonName}</Text>
</View>

CodePudding user response:

If you only want to display only one element of array, you don't need to use the .map() function

You can try this instead

const lesson1 = route.params.Lessons[0]

return (
    <View>
        <Text style={styles.lessonTitle}>Lesson 1</Text>
        <Text style={styles.lessonDescription}>{lesson1.lessonName}</Text>
    </View>
)

CodePudding user response:

Simply solved!

const LessonList = route.params.Lessons;

return (
    <View>
        <Text style={styles.lessonTitle}>Lesson 1</Text>
        <Text style={styles.lessonDescription}>{Lessons[0].lessonName}</Text>
    </View>
       )

I hope you find an answer :D

  • Related