Home > Software engineering >  How to break a loop inside inline if in next js
How to break a loop inside inline if in next js

Time:06-01

I would like to stop the loop inside bedsAssign.map if row.id is not equal to u.tenant_id but putting break; doesn't work.

{tenants.map((row) =>
                 bedsAssign.map(
                   (u) =>
                     row.id !== u.tenant_id && (
                       <MenuItem key={row.id} value={row.id}>
                         {row.fullName}
                       </MenuItem>
                        break; --> not working
                     )
                 )
               )}

CodePudding user response:

You can add filter before map to remove all bedsAssign items which are not matched with current row.id

{
  tenants.map((row) =>
    bedsAssign
      .filter((u) => row.id !== u.tenant_id)
      .map((u) => (
        <MenuItem key={row.id} value={row.id}>
          {row.fullName}
        </MenuItem>
      ))
  )
}

CodePudding user response:

You can not break any array methods like forEach, filter, map etc. If you encounter a scenario where you want your loop to break then you should use traditional for loop.

  • Related