I am trying to create a navbar with buttons that gain an 'activeTab' class if the browser route meets specific criteria for each button. For one of the buttons which takes a user to their profile, the activeTab class is added to the button when the browser is at the user page for the logged in user - code shown below:
className={
location.pathname === "/userDetails" ||
location.pathname === `/users/${userInfo.username}`
? "activeTab"
: null
}
The above works well. What is not working is trying to implement logic which makes another button the activeTab when the browser navigates to a user page which is NOT the logged in user. The logic I have in mind is something like this:
className={
location.pathname === "/exploreUsers" ||
location.pathname === `/users/${!userInfo.username}`
? "activeTab"
: null
}
or this:
className={
location.pathname === "/exploreUsers" ||
location.pathname === `/users/${*}`
? "activeTab"
: null
}
But I can't seem to get it to work. Any suggestions on the implementation here?
CodePudding user response:
I think the issue lies with your !userInfo.username
logic. That is returning a false or true value, and is not doing any comparison to the logged in user. So what that template literal is evaluating to is:
"users/false"
Instead, I think you could change the logic to do a comparison of the current user vs. the pathname. This will involve manipulating the pathname string to only look at the username portion.
ex:
className = {
location.pathname === "/exploreUsers" ||
location.pathname.split('/')[2] !== userInfo.username
? "activeTab"
: null
}
I'm splitting the pathname string on the /
character, which will return an array of strings that in between the slashes.
ex:
"/users/bobby".split('/') // => ['', 'users', 'bobby']
Then I call the 2nd index of that array (the 3rd value), which will be the username bobby
. From there I test that the current user does not equal the pathname user, and add the class accordingly.