skip to Main Content

I am trying to create a condition statement for the url that the user would click,
what i want to do is this, check if the message.sender.id === user_id, then i want to change the url to ${/inbox/}${message.reciever.id}${"/"} and if the message.sender.id !=== user_idi need url to be ${/inbox/}${message.sender.id}${"/"}

i don’t know the best way to do this becuase the url is supposed to be in a map

{
  message.map((message) => (
    <Link className="chat-contacts-item" to={message.sender.id === user_id && `${/inbox/}${message.reciever.id}${"/"}`}>
     <p className="float-left">{message.message}</p>
    </Link>
  )
)}
<Link className="chat-contacts-item" to={message.sender.id === user_id &&`${/inbox/}${ message.reciever.id}${'/'}`}> 
    Click Now
</Link>

This is the one I wrote, how to write else statement here

{message.sender.id === user_id && 
  `${/inbox/}${ message.reciever.id}${'/'}`
}

3

Answers


  1. You can define the link before returning the UI, its better readable code.
    Also, you can use same condition inside the to={..}

    We call it ternary operator something ? do this : else do this

    I hope this answer can help.

    {message.map((message) => {
     const link = message.sender.id === user_id ? `${/inbox/}${message.reciever.id}${"/"}` : `${/inbox/}${message.sender.id}${"/"}`
        return (<Link className="chat-contacts-item" to={link}>
                    <p className="float-left">{message.message}</p>
                </Link>
        )
    })}
    
    Login or Signup to reply.
  2. <Link 
      className="chat-contacts-item" 
      to={"/inbox/" + (message.sender.id === user_id ? message.reciever.id : message.sender.id) + "/"}
    >
        <p className="float-left">{message.message}</p>
    </Link>
    
    Login or Signup to reply.
  3. Cleanest way to do it in my opinion:

    {
        message.map((message) => (
            <Link
                className='chat-contacts-item'
                to={`${/inbox/}${
                    message.sender.id === user_id ? message.receiver.id : message.sender.id
                }${'/'}`}
            >
                <p className='float-left'>{message.message}</p>
            </Link>
        ));
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search