Checking content of a map function inside return section of React js

28 views Asked by At

How can I check in React if a map function is empty or not inside the return section? wanna check If it's empty, if so render an empty array, otherwise wanna render everything by mapping the content. I am asking because rendering an empty array this way will cause an exception..

return (

{functionName.map((...}

)

{functionName.map.lengh().? ...}

)

3

There are 3 answers

0
Radhames Leonardo On

Looks like the quickest way around this is by adding a "?" mark to the function name like this?

{functionName?.map.((item)=>...}

0
David Hype On

Is your function returning an array? Why not store what it returns in a usestate and map directly from the state using this

state?.map(your map goes here). That way, it will be more easier for you, cleaner and more readable.

0
Selaka Nanayakkara On

You can do this as follows:

import React from 'react';

const YourComponent = ({ yourArray }) => {
  
  const mappedArray = yourArray.map(item => (
    <p key={item.id}>{item.text}</p>
  ));

  
  return (
    <div>
      {mappedArray.length > 0 ? (  //check for array length here
        mappedArray
      ) : (
        <p>Nothing to display</p>
      )}
    </div>
  );
};

export default YourComponent;