I'm trying to make active buttons on the navbar so when an section is active it's highlighted.
For the colors I'm using custom colors and to change the state I'm using useState.
The problem is the buttons are working fine but Tailwind doesn't "stick" the active color the buttons.In the browser console i can see that useState updates the class text but nothing really shows in reality.
The Tailwind config
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
"./index.html",
"./src/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {
colors: {
'primary':'#01092E',
'secondary': '#011749',
'accent':'#6948B9',
},
backgroundImage: {
"hero-pattern": "url('/src/assets/herobg.jpg')",
},
},
},
plugins: [],
}
This is my component code
<ul className="list-none hidden sm:flex justify-center gap-10">
{navLinks.map((nav) => (
<li
key={nav.id}
className={`text-white hover:text-accent cursor-pointer text-[18px] font-medium px-4
${active === nav.title ? " text-accent " : " text-white "}`}
>
<Link
to={nav.id}
smooth={true}
duration={500}
offset={-80}
onClick={() => setActive(nav.title)}
>
{nav.title}
</Link>
</li>
))}
</ul>
The problem is that you are dynamically adding the tailwindCSS
classes in the div. TailwindCSS doesn't allow you to generate classes dynamically. So when you use the following to generate the class…
`className={`text-white hover:text-accent cursor-pointer text-[18px] font-medium px-4 ${active === nav.title ? " text-accent " : " text-white "}`}
…TailwindCSS will not pick that up as a valid TailwindCSS class and therefore will not produce the necessary CSS.
Instead, you must include the full name of the class in your source code. You can return the full value by using a function like this
function myDecoStyle(active) {
if(active === nav.title)
return "text-white hover:text-accent cursor-pointer text-[18px] font-medium px-4 text-accent ";
else
return "text-white hover:text-accent cursor-pointer text-[18px] font-medium px-4 text-white ";
}
where active
is the state you are passing here.
By doing it this way, the entire string for every class is in your source code, so TailwindCSS will know to generate the applicable CSS.
And use it like
<li
key={nav.id}
className={`${myDecoStyle(active)}`}
>
<Link
to={nav.id}
smooth={true}
duration={500}
offset={-80}
onClick={() => setActive(nav.title)}
>
{nav.title}
</Link>
</li>
Read more: https://tailwindcss.com/docs/content-configuration#class-detection-in-depth