how to add classes in react

<Link to="/" className={(pathname === '/') ? 'active' : ''} ><li>Home</li></Link>
<Link to="/" className={(pathname === '/') ? 'active' : ''} ><li>Home</li></Link>
i want to add classes to link tag but im not able to do it.. help
8 Replies
reeee
reeee2mo ago
classname attribute is already occupied, thats why
glutonium
glutonium2mo ago
Stack Overflow
How do I add an active class to a Link from React Router?
I've created a bootstrap-style sidebar using Link. Here is a snippet of my code: <ul className="sidebar-menu"> <li className="header">MAIN NAVIGATION</li> <li><Link ...
prophile
prophile2mo ago
Depending on what you want to do here, you might find the :local-link pseudo-class useful to be able to do styling directly in the CSS without needing to change the class name in React
Jochem
Jochem2mo ago
the part between {} is just a javascript expression. You can use a template string:
<Link to="/" className={`${(pathname === '/') ? 'active' : ''} yourClass`} ><li>Home</li></Link>
<Link to="/" className={`${(pathname === '/') ? 'active' : ''} yourClass`} ><li>Home</li></Link>
or an array if you don't like template strings:
<Link to="/" className={[(pathname === '/') ? 'active' : '', 'yourClass'].join(" ")} ><li>Home</li></Link>
<Link to="/" className={[(pathname === '/') ? 'active' : '', 'yourClass'].join(" ")} ><li>Home</li></Link>
missymae
missymae2mo ago
In react you use className, with the camelCase. classname without the capital letter is html, so react uses className.
reeee
reeee2mo ago
thanks for the help guys:thumbup:
b1mind
b1mind2mo ago
Better method is to use the aria attribute vs using a class.
b1mind
b1mind2mo ago
Ben Myers
Style with Stateful, Semantic Selectors
See how building with accessible semantics from the get-go can give you expressive, meaningful style hooks for free.
Want results from more Discord servers?
Add your server