Solution

To check empty array in react js, use array.length property and compare with 0 if length equal to zero it’s means array is empty.

array.length

The length property of an Array object represents the number of elements in that array.

The value of the length property is a non-negative integer with a value less than 232.

Snippet

In this snippet, we will create an array and use the array.length property, compare with zero and to show the message if array is empty in UI.

In React, you can check if an array is empty by using the .length property and checking if it is equal to 0. Here’s an example:

const myArray = [];

if (myArray.length === 0) {
  console.log('The array is empty');
} else {
  console.log('The array is not empty');
}

You can also use the Array.isArray() method to check if a value is an array, and then check its length to see if it is empty. Here’s an example:

const myValue = [];

if (Array.isArray(myValue) && myValue.length === 0) {
  console.log('The value is an empty array');
} else {
  console.log('The value is either not an array or is not empty');
}

Both of these methods will work in React to check if an array is empty.

Example

In this example, we will show the empty array message in UI if array is empty.

Let’s start coding…

import React, { useEffect, useState } from "react";
export default function App() {
  const [arr, setArr] = useState([]);

  useEffect(() => {
    console.log(arr.length == 0 ? "Empty Array" : "Have value")
  }, []);

  return (
    <div className="App">
      <h1>{`Is Array Empty?`}</h1>
      <p>{arr.length == 0 ? "Empty Array" : "Have value"}</p>
    </div>
  );
}

Output

Array, Empty

codesandbox