How to use dynamic route in react router 5

Issue #658

Declare routes, use exact to match exact path as finding route is from top to bottom. For dynamic route, I find that we need to use render and pass the props manually.

Declare Router as the rooter with Header, Content and Footer. Inside Content there is the Switch, so header and footer stay the same across pages

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from 'react-router-dom'

function Content() {
return (
<Switch>
<Route exact path="/about">
<About />
</Route>
<Route exact path="/">
<Home />
</Route>
<Route path='/book/:id' render={(props) => {
return ( <BookDetail {...props } /> )
}} />
<Route>
<NotFound />
</Route>
</Switch>
)
}

function App() {
return (
<div>
<Router>
<Header />
<Content />
<Footer />
</Router>
</div>
)
}

To trigger route request, use useHistory hook. Note that we need to declare variable, and not use useHistory().push directly

1
2
3
4
5
6
7
import { useHistory } from 'react-router-dom'

const history = useHistory()

<a onClick={() => {
history.push(`/book/${uuid}`)
}} >

To get parameters, use match

1
2
3
4
5
6
7
8
export default function BookDetail(props) {
const [ state, setState ] = useState({
book: null
})

const { match } = props
// match.params.id
}

Updated at 2020-06-03 05:07:00

Comments