React Router

React Router is the most used routing solution for React.

React Router Installation

1
npm install react-router-dom

First we need to wrap everything that gets rendered inside <BrowserRouter> element. we can do that in index.js

1
2
3
4
5
6
7
8
9
10
import {BrowserRouter} from "react-router-dom";

ReactDOM.render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>,
document.getElementById('root')
);

A <Switch> looks through all its children <Route> elements and renders the first one whose path matches the current URL. Use a <Switch> any time you have multiple routes, but you want only one of them to render at a time

Here the component will be display only when the path matches the current url. The exact attribute means the URL has to be exact match. Without the exact attribute, other URLs that contains “/“ is a match.

1
2
3
4
5
6
7
8
9
10
11
12
13
import {Switch, Route, Link} from "react-router-dom";

function App() {
return (
<div>
<Switch>
<Route path="/" component={Home} exact />
<Route path="/about" component={About} />
<Route path="/dashboard" component={Dashboard} />
</Switch>
</div>
);
}

Here is Home, About and Dashboard components

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function Home() {
return (
<div>
<h2>Home</h2>
</div>
);
}

function About() {
return (
<div>
<h2>About</h2>
</div>
);
}

function Dashboard() {
return (
<div>
<h2>Dashboard</h2>
</div>
);
}

You can add navigation links to help navigate the URLs

1
2
3
4
5
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/dashboard">Dashboard</Link></li>
</ul>

To try out the basic example: https://reactrouter.com/web/example/basic

Reference