Home > Software design >  I m trying to use a "if" statement but it doesnt run
I m trying to use a "if" statement but it doesnt run

Time:11-05

I have this components

and i have this code as the if sentence.

I have the same method in other project that works, can anyone help?

 it should only render the first one as addnewchat hte others ones should be avatars, if i take of the "!" only renders the avatars.

CodePudding user response:

You can change the syntax of if and else. Instead of using ternary operator directly after return keyword, use a parent tag, and then wrap your whole component inside it. Like

return (
<>
  {addNewChat ? (
   <div>if logic here</div>
    ) : (
   <div>else logic here</div>
  )}
</>
)

CodePudding user response:

calling component:

<div className="sidebar__chats">
        <SidebarChat addNewChat />
        <SidebarChat />
        <SidebarChat />
        <SidebarChat />
        <SidebarChat />
      </div> 

code:

return (
    <>
      {addNewChat ? (
        <div className="sidebarChat">
          <Avatar
            alt="João Espinheira"
            src={`https://avatars.dicebear.com/api/pixel-art/${seed}.svg`}
            sx={{ width: 38, height: 38 }}
          />
          <div className="sidebarChat__info">
            <h2>room name</h2>
            <p>last message...</p>
          </div>
        </div>
      ) : (
        <div onClick={createChat} className="sidebarChat">
          <h2>add new chat</h2>
        </div>
      )}
    </>
  );
}

i think the code should work, no?

  • Related