Not too familiar with the router, but I need NavLink functionality to set the active class in the parent element li , and not in the element a .
To implement this, I simply looked at the source code of NavLink and copied it into a new element. (An example using typescript, but about the same as js)
import * as React from 'react'; import { Link, withRouter, Route } from 'react-router-dom'; class LiNavLink extends React.Component<any, {}> { render() { const {to,exact, strict, activeClassName, className, activeStyle, style, isActive: getIsActive, ...rest } = this.props; return ( <Route path={typeof to === 'object' ? to.pathname : to} exact={exact} strict={strict} children={({ location, match }) => { const isActive = !!(getIsActive ? getIsActive(match, location) : match) return ( <li className={isActive ? [activeClassName, className].join(' ') : className} style={isActive ? { ...style, ...activeStyle } : style}> <Link to={to} {...rest} /> </li> ) }} /> ); } } export default LiNavLink;
Then use:
<ul> <LiNavLink activeClassName='active' exact={true} strict to="/example"><span>Active</span></LiNavLink> <LiNavLink activeClassName='active' exact={true} strict to="/example/archived"><span>Archived</span></LiNavLink> </ul>
I use HashRouter and for some reason I can’t understand, it does not update when the route changes, only when I rigidly 'refresh' the page, it updates how it should be.
I believe that it is never updated, because the props never change? So he doesn’t know to update himself?
How can I update this? Or is my problem somewhere else?
reactjs react-router-v4 react-router-dom
Kyle gobel
source share