Reputation: 33
I want to split my app in 2 different parts.
An exam list should link to a student list.
import React from 'react';
import ReactDOM from 'react-dom';
import {
BrowserRouter,
Link,
Route,
Switch,
useRouteMatch
} from 'react-router-dom';
// doesn't work
const ExamList = () => {
return (
<p>
current: ExamList, <Link to='/students'>to Students</Link>
</p>
);
};
// nested router
const Exams = () => {
let { path, url } = useRouteMatch();
return (
<BrowserRouter>
<Switch>
<Route exact path={path}>
<ExamList />
</Route>
</Switch>
</BrowserRouter>
);
};
// worked
const Students = () => {
return (
<p>
current: Students, <Link to='/'>to Exams</Link>
</p>
);
};
ReactDOM.render(
<BrowserRouter>
<Switch>
<Route exact path='/'>
<Exams />
</Route>
<Route path='/students'>
<Students />
</Route>
</Switch>
</BrowserRouter>,
document.getElementById('root')
);
"/"
click the link (to Students) doesn't render Students
component, but if I refresh the browser, the Students
component will be rendered currectly.
"/students"
click the link (to Exams) worked fine.
Upvotes: 1
Views: 427
Reputation: 15722
The problem is that you're not just nesting routes, but you're also nesting routers.
So change Exams
from this:
const Exams = () => {
let { path, url } = useRouteMatch();
return (
<BrowserRouter>
<Switch>
<Route exact path={path}>
<ExamList />
</Route>
</Switch>
</BrowserRouter>
);
};
to this:
const Exams = () => {
let { path, url } = useRouteMatch();
return (
<Switch>
<Route exact path={path}>
<ExamList />
</Route>
</Switch>
);
};
I recommend you take a look at this example for a good idea of where to go from here / how to approach nested routes in general.
Upvotes: 1