Hello Friends đź‘‹,

Welcome To Infinitbility! ❤️

This tutorial will help you to get the first element of your array into react native, here we will use simple array concepts available in javascript to get the first element of the array.

Let’s start today tutorial How to get the first element of the array in react native?

let assume you have like the below example.

var exampleArray = [
    {
      id: 1,
      name: "Infinit"
    },
    {
      id: 2,
      name: "Bility"
    }
];

Array provides the option to access elements using index. but before accessing element by index first verify array length. like the below example.

if(exampleArray.length > 0){
    let firstElement = exampleArray[0];

    console.log(firstElement, firstElement.name);
}

React Native get first element example

Here, i’m store exampleArray on state and write access code in render function.

import React, { Component } from "react";
import { Button, Text, View } from "react-native";

class FirstElement extends Component {
  state = { exampleArray: [
    {
      id: 1,
      name: "Infinit"
    },
    {
      id: 2,
      name: "Bility"
    }
]};

  render() {
  let firstElement = {};
  if(this.state.exampleArray.length > 0){
    firstElement = this.state.exampleArray[0];
  }
    return (
      <View>
        <Text>{firstElement.id}-{firstElement.name}</Text>
      </View>
    );
  }
}

export default FirstElement;

Output

React Native, access, first, element, Example