The Background color of the selected list item isn’t changing, only the text color is changing to white.
import { NavLink } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { MyContext } from "./links/MyContext.jsx";
import { useContext } from "react";
export default function HeaderLists() {
const [t] = useTranslation();
const { isDarkMode } = useContext(MyContext);
const activeLink = `bg-gradient-to-r from-cyan-800 to-blue-800 text-white `;
const normalLink = `hover:text-white hover:border-none ${
isDarkMode
? "text-white from-blue-950 to-cyan-900"
: "text-stone-600 border-stone-600"
}`;
return (
<ul className="mt-10 text-center">
<NavLink
to="/"
className={({ isActive }) => (isActive ? activeLink : normalLink)}
>
<li className="border-b-2 border-b-stone-500 p-5 hover:bg-gradient-to-r from-cyan-500 to-blue-600">
{t("tasks")}{" "}
</li>
</NavLink>
<NavLink
to="/Calendar"
className={({ isActive }) => (isActive ? activeLink : normalLink)}
>
<li className="border-b-2 border-b-stone-500 p-5 hover:bg-gradient-to-r from-cyan-500 to-blue-600">
{t("calendar")}
</li>
</NavLink>
<NavLink
to="/Settings"
className={({ isActive }) => (isActive ? activeLink : normalLink)}
>
<li className="border-b-2 border-b-stone-500 p-5 hover:bg-gradient-to-r from-cyan-500 to-blue-600">
{t("settings")}{" "}
</li>
</NavLink>
</ul>
);
}
When I select a list item such as Tasks, or Calendar, the selected item color is then changed to white, but the background color remains the same. It won’t change to the gradient I specified in activeLink const. I would like to know how I can fix it.
2
Answers
No need to use
active
state, updated your code as below:You are applying the style to the
NavLink
component, e.g. the anchor tag, instead of theli
element which still has its own CSS styling that includes a background color.Use the
children
function prop to access the link’sisActive
prop and apply the CSS to theli
element.Example Implementation: