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
reeeeOP3mo ago
classname attribute is already occupied, thats why
glutonium
glutonium3mo 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
prophile3mo 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
Jochem3mo 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
missymae3mo ago
In react you use className, with the camelCase. classname without the capital letter is html, so react uses className.
reeee
reeeeOP3mo ago
thanks for the help guys:thumbup:
b1mind
b1mind3mo ago
Better method is to use the aria attribute vs using a class.
b1mind
b1mind3mo 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