React-router: How I add class active for path '/' ? (react-router-dom)

Created on 22 Mar 2017  路  2Comments  路  Source: ReactTraining/react-router

Hello there,
I'm new react programmer, trying to learn with router.

I'm not sure how I use IndexRoute (react-router) with react-router-dom to use active for main page.
I do not know if it is correct to install react-route together with react-route-dom

Can someone explain what the solution is?

Code:

// BAD: Link Home is always active, in all pages.
<NavLink className='title' activeClassName='active' to='/'>Home</NavLink>
<NavLink className='title' activeClassName='active' to='/portfolio'>Portfolio</NavLink>

Most helpful comment

<IndexRoute> was a React Router v2/3 component. If you are using react-router-dom, you should only be importing from react-router-dom (not a strict requirement, but it keeps the imports simpler).

Your link to / is always active because every location begins with /. If you only want that link to be active when the pathname is /, then you should use the exact property.

// If you don't set an activeClassName, it defaults to "active"
<NavLink exact to='/' className='title'>Home</NavLink>

All 2 comments

<IndexRoute> was a React Router v2/3 component. If you are using react-router-dom, you should only be importing from react-router-dom (not a strict requirement, but it keeps the imports simpler).

Your link to / is always active because every location begins with /. If you only want that link to be active when the pathname is /, then you should use the exact property.

// If you don't set an activeClassName, it defaults to "active"
<NavLink exact to='/' className='title'>Home</NavLink>

Thanks a lot for help.

Was this page helpful?
0 / 5 - 0 ratings