I am having an issue with Nav
in react-bootstrap
code as follows:
import React from 'react';
import { NavLink, useRouteMatch } from 'react-router-dom';
import Container from 'react-bootstrap/Container';
import Nav from 'react-bootstrap/Nav';
import NavbarDefault from '../NavbarDefault/NavbarDefault';
import DashboardSwitch from '../DashboardSwitch/DashboardSwitch';
const Dashboard = () => {
const { url } = useRouteMatch();
return (
<div>
<div className="bg-light">
<Container fluid>
<NavbarDefault />
</Container>
</div>
<Container fluid>
<Nav className="mt-4" variant="tabs">
<Nav.Item>
<Nav.Link
as={NavLink}
to={`${url}`}
eventKey="link-1"
>
HOME
</Nav.Link >
</Nav.Item>
<Nav.Item>
<Nav.Link
as={NavLink}
to={`${url}/bonus`}
eventKey="link-2"
>
BONUS LIBRARY
</Nav.Link >
</Nav.Item>
<Nav.Item>
<Nav.Link
as={NavLink}
to={`${url}/newpage`}
eventKey="link-3"
>
NEW PAGE
</Nav.Link >
</Nav.Item>
<Nav.Item>
<Nav.Link
as={NavLink}
to={`${url}/mypages`}
eventKey="link-4">
MY PAGES
</Nav.Link >
</Nav.Item>
<Nav.Item>
<Nav.Link
as={NavLink}
to={`${url}/account`}
eventKey="link-5"
>
MY ACCOUNT
</Nav.Link >
</Nav.Item>
</Nav>
</Container>
<DashboardSwitch />
</div>
);
};
export default Dashboard;
const DashboardSwitch = () => {
const { path } = useRouteMatch();
return (
<Switch>
<ProtectedRoute exact path={`${path}`} component={Home} />
<ProtectedRoute exact path={`${path}/home`} component={Home} />
<ProtectedRoute exact path={`${path}/bonus`} component={Bonuses} />
<ProtectedRoute exact path={`${path}/newpage`} component={NewPage} />
<ProtectedRoute exact path={`${path}/mypages`} component={MyPages} />
<ProtectedRoute exact path={`${path}/account`} component={Account} />
<Route path="*"><NotFound /></Route>
</Switch>
);
}
Navigation between pages seems to work, but for the tab UI, the HOME tab is always selected:
I already removed the defaultActiveKey
prop but the issue still persists. What am I doing wrong here?
It is because every path matches the ${url}
path.
For instance, if you have a page called /test
and other called /test-2
, clicking on the page that goes to /test-2
would activate the tab that goes to /test
too, since /test
is included in the /test-2
.
Pass the prop exact
to you HOME
NavLink and you will not see it selected anymore unless the path is exact ${url}
.
<Nav.Link
as={NavLink}
to={`${url}`}
eventKey="link-1"
exact // add this
>
HOME
</Nav.Link >