JIYIK CN >

Current Location:Home > Learning > WEB FRONT-END > React >

Get the first element of an array in React.js

Author:JIYIK Last Updated:2025/03/16 Views:

In React, square brackets are used to get the first element of an array, e.g. const first = arr[0];the array element with index 0 is the first element in the array. If the array is empty, undefinedthe value is returned.

import {useState} from 'react';

const App = () => {
  const [state, setState] = useState([
    {id: 1, name: 'Alice'},
    {id: 2, name: 'Bob'},
  ]);

  const first = state[0];

  return (
    <div>
      <h2>id: {first?.id}</h2>
      <h2>name: {first?.name}</h2>
    </div>
  );
};

export default App;

We access the element at index 0 to get the first element of the array.

Indexes in JavaScript are zero-based, so the first element in an array has index 0 and the last element has index arr.length - 1.

请注意?., we used the optional chaining operator when accessing the property of the array element at index 0 .

If the reference is null ( null or undefined ), the optional chaining ?.operator short-circuits.

In other words, if the first variable stored an undefined value, we will short-circuit instead of trying to access a property of an undefined value and getting a runtime error.

We can also use if statements.

import {useState} from 'react';

const App = () => {
  const [state, setState] = useState([
    {id: 1, name: 'Alice'},
    {id: 2, name: 'Bob'},
  ]);

  const first = state[0];

  // 👇️ Make sure first is not undefined
  if (first != undefined) {
    console.log(first.id);
    console.log(first.name);
  }

  return (
    <div>
      <h2>id: {first?.id}</h2>
      <h2>name: {first?.name}</h2>
    </div>
  );
};

export default App;

This is necessary unless we are sure the array is not empty.

If we try to access an array at an index that doesn't exist, we will get an undefined value.

const arr = [];

console.log(arr[0]); // 👉️ undefined

If we try to access a property or call a method on an undefined value, we will receive a runtime error.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:https://www.jiyik.com/en/xwzj/web_9646.html

Related Articles

React Tutorial - Transferring Props

Publish Date:2025/03/16 Views:185 Category:React

React transfers Props. Props are generated when components are encapsulated. Components expose some properties (Props) to the outside world to complete some functions.

React Tutorial: Props Anti-Pattern

Publish Date:2025/03/16 Views:183 Category:React

React's Props anti-pattern, using Props to generate state in getInitialState is an anti-pattern - Anti-Pattern.

React Tutorial - Props Validation

Publish Date:2025/03/16 Views:99 Category:React

Props validation is a very useful way to use components correctly. It can avoid many bugs and problems as your application becomes more and more complex. In addition, it can make your program more readable.

Why do you need to bind event handlers in React Class Components?

Publish Date:2025/03/16 Views:58 Category:React

When using React, we must have come across control components and event handlers. We need to use `.bind()` in the constructor of the custom component to bind these methods to the component instance. As shown in the following code:

Solution to the error "does not contain a default export" in React

Publish Date:2025/03/16 Views:187 Category:React

When we try to use `default import` to import from a module that does not have a `default export`, we get a "does not contain a default export" error. To fix the error, make sure the module has named exports and wrap the import in curly braces, e.g.

Solve the Module not found: Can't resolve 'react-bootstrap' error

Publish Date:2025/03/16 Views:85 Category:React

To resolve the error "Module not found: Error: Can't resolve 'react-bootstrap'", make sure to install the react-bootstrap package by opening a terminal in the root directory of the project and running the command `npm install react-bootstrap bootstrap

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial