Home > front end >  How do i write a conditional for the possibility of an empty array
How do i write a conditional for the possibility of an empty array

Time:10-27

I have a users list that im mapping over in a little side bar. Theres a possiblity that there can be no users. So I would like the side bar to say none if theres no users. I tried the below method but it seems like its still registering the user, even if its 0. I've tried (user === null) and (user.length < 1) but just cant seem to get it.

{usersList.map((user) => {
  if (!user) {
    return <h5>none</h5>;
  } else {
    return (
      <h5
        key={user}
      >
        <Link
          to={`/user/${user}`}
          style={{ textDecoration: "none"}}
        >
          {user}
        </Link>
      </h5>
    );
  }
})}

CodePudding user response:

Check if the array length is greater than 0: if so, display the list, otherwise display "none"

You can do this with a simple ternary operator:

condition ? truthy : falsey
{usersList.length > 0 ? (
  usersList.map((user) => (
    <h5 key={user}>
      <Link to={`/user/${user}`} style={{ textDecoration: "none" }}>
        {user}
      </Link>
    </h5>
  ))
) : (
  <h5>none</h5>
)}

CodePudding user response:

You can use the ternary operator:

{
 userList?.length > 0 ?  <h5
    key={user}
  >
    <Link
      to={`/user/${user}`}
      style={{ textDecoration: "none"}}
    >
      {user}
    </Link>
  </h5> :
 <h5>No Users</h5>
}

or can use &&

{(!userList || userList?.length === 0) &&  <h5>No Users</h5>}
{userList?.length > 0 && <h5
    key={user}
  >
    <Link
      to={`/user/${user}`}
      style={{ textDecoration: "none"}}
    >
      {user}
    </Link>
  </h5>}
  • Related