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='/' component={Forecast} />
<Route exact path='/map' component={Map} />
</Switch>
</Router>
</Provider>
)
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"
This works for this common errors:
In React Router v6, activeClassName will be removed and you should use the function className to apply classnames to either active or inactive NavLink components.
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>
for react Navlink a simple
a.active{color:red;}
will work automatically, with Navlink even cursor:pointer is by default grabbing. no
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.