I'm using Reactstrap and React-router 4.0.0-beta.6 in the educational project that is located on gitlab with custom domain.
According to Reactstrap docs: that's the way I should use active navlink
import { NavLink } from 'reactstrap'
...
<NavLink href="#" active = true >Link< /NavLink>
According to React-router v4 docs:
import { NavLink } from 'react-router-dom'
...
<NavLink to="/about" activeClassName="active">About</NavLink>
So how should I do implement navlink active state and use react-router?
To use both, you'll need to rename one of those imports and use the tag prop in reactstrap NavLink. You won't be able to use the active prop on reactstrap NavLink because that logic exists in react router NavLink.
Here's what it should look like:
import { NavLink } from 'reactstrap';
import { NavLink as RRNavLink } from 'react-router-dom';
<NavLink to="/about" activeClassName="active" tag={RRNavLink}>About</NavLink>
More info here: https://github.com/reactstrap/reactstrap/issues/336
By default active
class is used. You can simply use exact
boolean property to match the exact path.
import { NavLink } from 'reactstrap';
import { NavLink as RRNavLink } from 'react-router-dom';
<NavLink exact to="/about" tag={RRNavLink}>About</NavLink>
Have a look on the source code of react-router.NavLink component: https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/modules/NavLink.js
Since you are using reactstrap to handle styling for the navbar, you don't, and shouldn't need to rely on NavLink from react-router to do the same thing.
You can use Link from react-router instead, which deals with the routing only, and doesn't add the 'active' className when it is selected. But that's fine, because bootstrap's NavLink will do the styling for you.
import { NavLink } from 'reactstrap';
import { Link } from 'react-router-dom';
<NavLink><Link to="/about">About</Link></NavLink>
My advice is to avoid <Link>
, <NavLink>
, and tag
all together when working with React Router v4 and Reactstrap (Bootstrap). I really think all three should be deprecated, especially the tag
attribute. Trying to mix-in React Router's <Link>
and <NavLink>
into Reactstrap components leads to unforeseen style issues with Bootstrap (for example: https://github.com/reactstrap/reactstrap/issues/562).
I've found that from a style standpoint, it's better to use the React Router v4 <Route>
component, and pass the history
prop to the Reactstrap component.
import { Route } from 'react-router-dom';
import { Button } from 'reactstrap';
<Route
render={props =>
<Button role="button"
onClick={() => props.history.push("/endpoint")}>
</Button>}
/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With