Home > OS >  trying to run "if" sentence and not working, react
trying to run "if" sentence and not working, react

Time:11-09

I m calling the component like this

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

i m expecting all avatars except the first one that should say "add new chat". this is the code of the component

function SidebarChat(addNewChat) {
  const [seed, setSeed] = useState("");
  useEffect(() => {
    setSeed(Math.floor(Math.random() * 5000));
  }, []);

  const createChat = () => {
    const roomName = prompt("please enter the name for chat");
    if (roomName) {
      //do some clever database stuff
    }
  };

  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>
      )}
    </>
  );
}

export default SidebarChat;

can anyone help, i think this should work but not entereing the else condition. does anyone knows why? when i dont use the " ! " in the addnewchat every single one turn into avatars, and doesnt do the else statement. i dont understand why cant i use like this, since the code is ok

currently i have this outcome image1, and it should be something like this image2

CodePudding user response:

Change the first line of the component to

function SidebarChat({addNewChat}) {

The argument to a component is an object containing all the props, so you need to destructure it to access a given prop.

  • Related