React Router (v4) Navbar
For those who are working with react-bootstrap v4 (using 1.0.0-beta.5 currently) and react-router-dom v4 (4.3.1) just use "as" prop from Nav.Link, here is full example:
import { Link, NavLink } from 'react-router-dom'
import { Navbar, Nav } from 'react-bootstrap'
<Navbar>
{/* "Link" in brand component since just redirect is needed */}
<Navbar.Brand as={Link} to='/'>Brand link</Navbar.Brand>
<Nav>
{/* "NavLink" here since "active" class styling is needed */}
<Nav.Link as={NavLink} to='/' exact>Home</Nav.Link>
<Nav.Link as={NavLink} to='/another'>Another</Nav.Link>
<Nav.Link as={NavLink} to='/onemore'>One More</Nav.Link>
</Nav>
</Navbar>
Here is working example: https://codesandbox.io/s/3qm35w97kq
This is how I implement it, it works with"react-router-dom": "^4.2.2"
"react-bootstrap": "^0.31.5"
import { Link } from 'react-router-dom';
import { NavBar, Nav, NavItem} from 'react-bootstrap';
const NavBar = ({location}) => (
<NavBar>
<Nav>
<NavItem componentClass={Link} href="/artists" to="/artists" active={location.pathname === '/artists'}>Artists</NavItem>
<NavItem componentClass={Link} href="/stages" to="/stages" active={location.pathname === '/stages'}>Stages</NavItem>
</Nav>
<NavBar>
// ...
Where location
is the native property of a Route
: https://reacttraining.com/react-router/web/api/location
Hope this helps.
EDIT: Just noticed that you're using react-materialize
so my answer is probably not applicable to your question.
On your Nav component, try using react router's <NavLink>
instead of <Link>
.
<NavLink>
is a special version of the <Link>
that will add styling attributes to the rendered element when it matches the current URL.
<NavLink>
has activeClassName and activeStyle properties that you can use them to apply style to your active navigation item.
For example a basic navigation would be like this:
<nav>
<NavLink activeStyle={{color: 'red'}} to="/foo">Foo</NavLink>
<NavLink activeStyle={{color: 'red'}} to="/bar">Bar Group</NavLink>
<NavLink activeStyle={{color: 'red'}} to="/another-foo">Another Foo</NavLink>
<NavLink activeStyle={{color: 'red'}} to="/another-bar">Another Bar</NavLink>
</nav>
Where activeStyle represents the style to apply to the element when it is active.
And below the same example via activeClassName:
<nav>
<NavLink activeClassName="selected" to="/foo">Foo</NavLink>
<NavLink activeClassName="selected" to="/bar">Bar Group</NavLink>
<NavLink activeClassName="selected" to="/another-foo">Another Foo</NavLink>
<NavLink activeClassName="selected" to="/another-bar">Another Bar</NavLink>
</nav>
activeClassName is the class to give the element when it is active. For this example I choose it to be selected
. By default in react-router v4 given class for the active state is active
.
Find more about <NavLink>
on react-router v4 documentation