Navlink
// React Router v6
import { NavLink } from 'react-router-dom';
function NavBar() {
// inline or css classes
let activeStyle = { color: 'green', textDecoration: 'underline' };
let activeClass = 'activated';
return (
<nav>
<ul>
<li>
<NavLink
to='messages'
style={({ isActive }) => isActive ? activeStyle : undefined}>
Messages
</NavLink>
</li>
<li>
<NavLink
to='tasks'
className={({ isActive }) => isActive ? activeClass : undefined}>
Tasks
</NavLink>
</li>
</ul>
</nav>
);
}
// Special kind of <Link> that knows when it is 'active'
// the styling applies to a <NavLink> when route it links to
// is currently selected.
/*
index.css
a, .nav-link { color: 'blue', text-decoration: 'none' }
.activated { color: 'green', text-decoration: 'underline' }
*/
// React Router v5
function NavBar() {
return (
<nav>
<ul>
<li>
<NavLink
to='/messages'
style={{ color: 'blue', textDecoration: 'none' }}
activeStyle={{ color: 'green', textDecoration: 'underline' }}>
Messages
</NavLink>
</li>
<li>
<NavLink
to='tasks'
className='nav-link'
activeClassName='activated'>
Tasks
</NavLink>
</li>
</ul>
</nav>
);
}
Coffee Addict