I am using react-router-dom, and I need to make red a link when the url match, in my up I have two urls /
=> home and /map
.
With the current code, I am able to route to different page but the NavLink
is not being highlighted when the url is changed in the browser. Any ideas how to fix it.
import React from 'react'
import { NavLink, Route } from 'react-router-dom'
const Navigation = ({ onClick, id, title, tooltip, url }) => {
return (
<div onClick={onClick} alt={tooltip}>
{ <Route path={url} exact children={({ match }) => (
<div style={match ? {color: 'red'} : {}}>
{match ? '> ' : ''}<NavLink to={url}>{title}</NavLink>
</div>
)} />}
</div >
)
}
export default Navigation
const Root = ({ store }) => (
<Provider store={store}>
<Router>
<Switch>
<Route exact path='/' ponent={Forecast} />
<Route exact path='/map' ponent={Map} />
</Switch>
</Router>
</Provider>
)
I am using react-router-dom, and I need to make red a link when the url match, in my up I have two urls /
=> home and /map
.
With the current code, I am able to route to different page but the NavLink
is not being highlighted when the url is changed in the browser. Any ideas how to fix it.
import React from 'react'
import { NavLink, Route } from 'react-router-dom'
const Navigation = ({ onClick, id, title, tooltip, url }) => {
return (
<div onClick={onClick} alt={tooltip}>
{ <Route path={url} exact children={({ match }) => (
<div style={match ? {color: 'red'} : {}}>
{match ? '> ' : ''}<NavLink to={url}>{title}</NavLink>
</div>
)} />}
</div >
)
}
export default Navigation
const Root = ({ store }) => (
<Provider store={store}>
<Router>
<Switch>
<Route exact path='/' ponent={Forecast} />
<Route exact path='/map' ponent={Map} />
</Switch>
</Router>
</Provider>
)
Share
Improve this question
edited Sep 6, 2017 at 13:00
Radex
asked Sep 6, 2017 at 12:37
RadexRadex
8,64724 gold badges61 silver badges97 bronze badges
1
- Yes correct, I want to mark as active the link which map the URL. Thanks – Radex Commented Sep 6, 2017 at 12:43
3 Answers
Reset to default 2This works for this mon errors:
- 'isActive' is not defined no-undef
- activeClassName is not working in NavLink
In React Router v6, activeClassName will be removed and you should use the function className to apply classnames to either active or inactive NavLink ponents.
Reference is here.
Use normally the imports like:
import { NavLink, Route } from 'react-router-dom'
and in NavLinks use:
<NavLink
to="/text"
className={({ isActive }) => (isActive ? 'active' : 'inactive')}
>
Text
</NavLink>
Your approach is bit confusing. But if you want to highlight the active link which is navigated you can simply add activeClassName to your NavLink. Something like this
<NavLink to={url} exact activeClassName="activeLink" style=>{title}</NavLink>
CSS for activeLink:
.activeLink {
color: red;
}
* react-router-dom: "^4.1.2"
for react Navlink a simple
a.active{color:red;}
will work automatically, with Navlink even cursor:pointer is by default grabbing. no