1import React from 'react'
2import ReactDOM from 'react-dom'
3import { useParams } from 'react-router-dom'
4
5function BlogPost() {
6 // We can call useParams() here to get the params,
7 // or in any child element as well!
8 let { slug } = useParams()
9 // ...
10}
11
12ReactDOM.render(
13 <Router>
14 <div>
15 <Switch>
16 {/* No weird props here, just use
17 regular `children` elements! */}
18 <Route path="/posts/:slug">
19 <BlogPost />
20 </Route>
21 </Switch>
22 </div>
23 </Router>,
24 document.getElementById('root')
25)
1import { useLocation } from 'react-router-dom'
2
3// Location is, for example: http://localhost:3000/users/new
4
5// Care! MyComponent must be inside Router to work
6const MyComponent = () => {
7 const location = useLocation()
8
9 // location.pathname is '/users/new'
10 return <span>Path is: {location.pathname}</span>
11}
12
13export default MyComponent
1import React from "react";
2import ReactDOM from "react-dom";
3import {
4 BrowserRouter as Router,
5 Switch,
6 Route,
7 useParams
8} from "react-router-dom";
9
10function BlogPost() {
11 let { slug } = useParams();
12 return <div>Now showing post {slug}</div>;
13}
14
15ReactDOM.render(
16 <Router>
17 <Switch>
18 <Route exact path="/">
19 <HomePage />
20 </Route>
21 <Route path="/blog/:slug">
22 <BlogPost />
23 </Route>
24 </Switch>
25 </Router>,
26 node
27);
28
1import {
2 BrowserRouter as Router,
3 Switch,
4 Route,
5 useParams
6} from "react-router-dom";
7
8function BlogPost() {
9 let { slug } = useParams();
10 return <div>Now showing post {slug}</div>;
11}
12
13ReactDOM.render(
14 <Router>
15 <Switch>
16 <Route exact path="/">
17 <HomePage />
18 </Route>
19 <Route path="/blog/:slug">
20 <BlogPost />
21 </Route>
22 </Switch>
23 </Router>,
24 node
25);
26