Home > Enterprise >  React break .map() in condition rendering
React break .map() in condition rendering

Time:07-15

How can I use break to break a .map() function when condition rendering is true ?

This is my example code

  {messages.length >= 1 ? (
   <div>
    {messages.reverse().map((e) => (
      e.senderName[0] == displayName[0] ? (<p>Status: {e.message}</p>) : null
    ))} 
   </div>
  ) : (<p>Status: Verifying...</p>)}

The problem is in messages array is gonna have a new message add every 60 second and I want to display a new message on my screen that has been add in every 60 second

Then I want to break .map() function after a new message has been add to messages array and display on my screen

What I want is like this enter image description here

But the problem is like this enter image description here

CodePudding user response:

you can't use break to stop .map() method. I see that you are trying to render messages if message belongs to current user.

I can recommend you to filter the messages first, then render the filtered array with mapping. Like:

const usersMessages = messages.reverse().filter((e) => (e.senderName[0] === displayName[0]);

return (
<div>
{usersMessages.length > 0 ? (usersMessages.map(e =>{
return((<p>Status: {e.message}</p>))
})) : <p>Status: Verifying...</p>)}
</div>
)

Of course you must have a part in your code that updates the messages array and triggers a re-render when data is updated.

  • Related