Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Active link with React-Router?

I'm trying out React-Router (v4) and I'm having issues starting off the Nav to have one of the Link's be active. If I click on any of the Link tags, then the active stuff starts working. However, I'd like for Home Link to be active as soon as the app starts since that is the component that loads at the / route. Is there any way to do this?

Here is my current code:

const Router = () => (   <BrowserRouter>     <div>       <Nav>         <Link activeClassName='is-active' to='/'>Home</Link> {/* I want this to start off as active */}         <Link activeClassName='is-active' to='/about'>About</Link>       </Nav>        <Match pattern='/' exactly component={Home} />       <Match pattern='/about' exactly component={About} />       <Miss component={NoMatch} />     </div>   </BrowserRouter> ) 
like image 444
Saad Avatar asked Dec 13 '16 22:12

Saad


People also ask

How do you make links stay active when clicked in React?

you have to use NavLink. ALSO! the exact={true} is exactly right too. Otherwise the first link that renders will not re render when you click other links causing home to always be active.

How do I show active routes in React?

Update for React v16.8+ & React Router v5+: log(location. pathname); // outputs currently active route return children; }; export default Main; Wrap your components with withRouter and then you can access the current active route using this. props.


1 Answers

<Link> no longer has the activeClassName or activeStyle properties. In react-router v4 you have to use <NavLink> if you want to do conditional styling:

const Router = () => (   <BrowserRouter>     <div>       <Nav>         <NavLink exact={true} activeClassName='is-active' to='/'>Home</NavLink>         <NavLink activeClassName='is-active' to='/about'>About</NavLink>       </Nav>        <Match pattern='/' exactly component={Home} />       <Match pattern='/about' exactly component={About} />       <Miss component={NoMatch} />     </div>   </BrowserRouter> ) 

I added an exact property to the home <NavLink>, I'm fairly sure that without it, the home link would always be active since / would match /about and any other pages you have.

like image 164
worc Avatar answered Oct 09 '22 14:10

worc