React state array: get length example

React state array: get length example

In this short article, we'll look at how to get the length of an array or state array in React.

Because React is a JavaScript library for rendering user interfaces, it focuses solely on rendering the UI and does not provide additional utilities for working with arrays or other similar tasks. As a consequence, you must rely primarily on JavaScript's built-in methods and APIs.

JavaScript' Array length by example in React

We'll see how to get the length of an array in React and JavaScript in this example. JavaScript includes various built-in methods for determining the length of an array; let's look at how to use one in a React example.

The Array's length property sets or returns the count of elements in the array. The obtained value is an unsigned 32-bit integer that is always greater than the array's highest index.

Create an index.js file and add the following code:

import React from 'react'

class App extends React.Component {

    render(){
        const array = ["React","is", "awesome", "!"];
        const length = array.length;
        return(
            <div>
                <p>Array length is { length }.</p>
            </div>
        )
    }

}

ReactDOM.render(<App />, document.getElementById("root"));

In the render() method, we simply define a JavaScript array then we get the length of the array using the Array.length method. Finally we return a JSX markup to didplay the length of the array.

You should import React and ReactDOM in your project and use ReactDOM to mount the component in the DOM:

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

Here we are using React 16.8 but you can also use the latest React version available. You can already upgrade to React 18.

In the same way, you can get the length of the array in React state as follows:

class App extends React.Component {
  state = {
    array: ["Hello", "React"]
  };


  render() {
    return (
      <div>
        <p>React State Array Length: {this.state.array.length}</p>        
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));

Conclusion

In this short example we looked at how to find out the length of an array or a state array in the React library using the Array.length method of JavaScript. We've seen how to get the length of a local array or state array and render the result in the DOM.

The fact that React is a JavaScript library for rendering user interfaces means that it is solely concerned with rendering the UI and does not provide any other functionality such as working with arrays or performing other similar tasks. Consequently, you must rely on the JavaScript methods and APIs that have been built into the language.