I am using "react-router-dom": "^6.4.1"
with my current app. I am getting 2 issues.
when navigating to other page, home page active
class not removed. still both new page and home page are having active
class name.
I am always with NotFound
page. even when i click on other page, I am in the NotFound
page.
Anyone help me to understand the issue what I am running with?
Code for scenario 1:
{links.map(({ name, path }, index) => {
return (
<li key={index}>
<NavLink
onClick={() =>
setIsNavShowing((prev) => !prev)
}
to={path}
className={({ isActive }) =>
isActive ? 'active-nav' : ''
}
>
{name}
</NavLink>
</li>
);
})}
Senario 2:
const App: FC = () => {
return (
<BrowserRouter>
<Navbar />
<Routes>
<Route path="about" element={<About />} />
<Route path="contact" element={<Contact />} />
<Route path="gallery" element={<Gallery />} />
<Route path="home" element={<Home />} />
<Route path="plans" element={<Plans />} />
<Route path="trainers" element={<Trainers />} />
<Route path="*" element={<NotFound />} />
</Routes>
</BrowserRouter>
);
};
Link array:
export const links:TypeLink[] = [
{
name: "Home",
path: '/'
},
{
name: "About",
path: '/about'
},
{
name: "Gallery",
path: '/gallery'
},
{
name: "Plans",
path: '/plans'
},
{
name: "Trainers",
path: '/trainers'
},
{
name: "Contact",
path: '/contact'
}
]
The active NavLink
link issue can be resolved by specifying the end
prop.
declare function NavLink( props: NavLinkProps ): React.ReactElement; interface NavLinkProps extends Omit< LinkProps, "className" | "style" | "children" > { caseSensitive?: boolean; children?: | React.ReactNode | ((props: { isActive: boolean }) => React.ReactNode); className?: | string | ((props: { isActive: boolean; }) => string | undefined); end?: boolean; style?: | React.CSSProperties | ((props: { isActive: boolean; }) => React.CSSProperties); }
If the
end
prop is used, it will ensure this component isn't matched as "active" when its descendant paths are matched.
{links.map(({ name, path }, index) => {
return (
<li key={index}>
<NavLink
onClick={() =>
setIsNavShowing((prev) => !prev)
}
end // <-- specify end prop
to={path}
className={({ isActive }) => (isActive ? "active-nav" : "")}
>
{name}
</NavLink>
</li>
);
})}
The only issue I see with the routes is that the Home
component is being rendered on "/home"
instead of "/"
like the link is linking to.
<Routes>
<Route path="about" element={<About />} />
<Route path="contact" element={<Contact />} />
<Route path="gallery" element={<Gallery />} />
<Route path="/" element={<Home />} /> // <-- render on "/" instead of "/home"
<Route path="plans" element={<Plans />} />
<Route path="trainers" element={<Trainers />} />
<Route path="*" element={<NotFound />} />
</Routes>
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.