1import React from "react";
2import {
3 BrowserRouter as Router,
4 Switch,
5 Route,
6 Link,
7 useRouteMatch,
8 useParams
9} from "react-router-dom";
10
11export default function App() {
12 return (
13 <Router>
14 <div>
15 <ul>
16 <li>
17 <Link to="/">Home</Link>
18 </li>
19 <li>
20 <Link to="/about">About</Link>
21 </li>
22 <li>
23 <Link to="/topics">Topics</Link>
24 </li>
25 </ul>
26
27 <Switch>
28 <Route path="/about">
29 <About />
30 </Route>
31 <Route path="/topics">
32 <Topics />
33 </Route>
34 <Route path="/">
35 <Home />
36 </Route>
37 </Switch>
38 </div>
39 </Router>
40 );
41}
42
43function Home() {
44 return <h2>Home</h2>;
45}
46
47function About() {
48 return <h2>About</h2>;
49}
50
51function Topics() {
52 let match = useRouteMatch();
53
54 return (
55 <div>
56 <h2>Topics</h2>
57
58 <ul>
59 <li>
60 <Link to={`${match.url}/components`}>Components</Link>
61 </li>
62 <li>
63 <Link to={`${match.url}/props-v-state`}>
64 Props v. State
65 </Link>
66 </li>
67 </ul>
68
69 {/* The Topics page has its own <Switch> with more routes
70 that build on the /topics URL path. You can think of the
71 2nd <Route> here as an "index" page for all topics, or
72 the page that is shown when no topic is selected */}
73 <Switch>
74 <Route path={`${match.path}/:topicId`}>
75 <Topic />
76 </Route>
77 <Route path={match.path}>
78 <h3>Please select a topic.</h3>
79 </Route>
80 </Switch>
81 </div>
82 );
83}
84
85function Topic() {
86 let { topicId } = useParams();
87 return <h3>Requested topic ID: {topicId}</h3>;
88}
89
1npm install react-router-dom
2import {BrowserRouter, Switch, Route, Link} from "react-router-dom"
3import React from "react";
4import {
5 BrowserRouter as Router,
6 Switch,
7 Route,
8 Link
9} from "react-router-dom";
10
11export default function App() {
12 return (
13 <Router>
14 <div>
15 <nav>
16 <ul>
17 <li>
18 <Link to="/">Home</Link>
19 </li>
20 <li>
21 <Link to="/about">About</Link>
22 </li>
23 <li>
24 <Link to="/users">Users</Link>
25 </li>
26 </ul>
27 </nav>
28
29 {/* A <Switch> looks through its children <Route>s and
30 renders the first one that matches the current URL. */}
31 <Switch>
32 <Route path="/about">
33 <About />
34 </Route>
35 <Route path="/users">
36 <Users />
37 </Route>
38 <Route path="/">
39 <Home />
40 </Route>
41 </Switch>
42 </div>
43 </Router>
44 );
45}
46
47function Home() {
48 return <h2>Home</h2>;
49}
50
51function About() {
52 return <h2>About</h2>;
53}
54
55function Users() {
56 return <h2>Users</h2>;
57}
58
1// using ES6 modulesimport { BrowserRouter, Route, Link } from "react-router-dom"; // using CommonJS modulesconst BrowserRouter = require("react-router-dom").BrowserRouter;const Route = require("react-router-dom").Route;const Link = require("react-router-dom").Link;