I have created a header menu on which I want to show the border-bottom of the red color & text-color of black on the active menu. To achieve this I am using the useLocation()
function from the react-router-dom
but it is not showing up.
import { useLocation, useNavigate } from "react-router-dom";
const Header = () => {
const location = useLocation();
const navigate = useNavigate();
const checkPath = (path) => {
console.log(location.pathname, path);
if (path === location.pathname) return true;
else return false;
}
return (
<div className="bg-white border-b shadow-sm sticky top-0 z-50">
<header className="flex justify-between items-center px-3 max-w-6xl mx-auto">
<div>
<img src="https://static.rdc.moveaws.com/images/logos/rdc-logo-default.svg" alt="" className="h-5 cursor-pointer" onClick={() => navigate('/')} />
</div>
<div>
<ul className="flex gap-5">
<li className={`py-6 text-sm border-b-[3px] text-gray-500 font-semibold border-b-transparent ${checkPath("/") && "text-black border-b-red-500"} cursor-pointer`} onClick={() => navigate('/')}>Home</li>
<li className={`py-6 text-sm border-b-[3px] text-gray-500 font-semibold border-b-transparent ${checkPath("/offers") && "text-black border-b-red-500"} cursor-pointer`} onClick={() => navigate('/offers')}>Offers</li>
<li className={`py-6 text-sm border-b-[3px] text-gray-500 font-semibold border-b-transparent ${checkPath("/sign-in") && "text-black border-b-red-500"} cursor-pointer`} onClick={() => navigate('/sign-in')}>Sign In</li>
</ul>
</div>
</header>
</div>
)
}
export default Header
This is the GitHub link of the repository: https://github.com/olifarhaan/griha-milan
How to replicate the issue
Clone the repository on your local machine.
Run the following script npm install
I tried everything but the I think the tailwind css is not overriding the previous classes I used console.log after && then it is showing in the console.
2
Answers
The problem is that you already have classes that apply
color
andborder-bottom-color
. WhencheckPath()
returnstrue
, the element then has two classes that applycolor
andborder-bottom-color
each. Then you are at the mercy of the CSS order to which CSS rule applies, and alas, it seems the "static" classes appear later in the CSS and thus no visual changes are visible.To resolve your predicament, consider altering the classes such that only one class is applied for a property (with the same variant) at any one time:
So you actually have 2 issues. Like @Wongjn said, you are creating a CSS conflict, and it is better to address it with a ternary operator (like he did), i.e.,
But what you also did wrong is combining classes. So with Tailwind, you need to specify each characteristic of a element separately. So once you show that the border is on the bottom with
border-b-[3px]
then any other characteristic applied to the border will be added to the visible part of the border only (which is the bottom in this case). So your code should be:Making your final classNames: