EN
React / react-router 5 - basic routing example
3 points
In this article, we would like to show you a basic routing example in React.
To use routing in React, the first thing you need to do is install react-router-dom@5
with command line inside your project.
xxxxxxxxxx
1
npm install react-router-dom@5
Then you have to import:
BrowserRouter
(e.g. asRouter
) - that contains core routing logic,Switch
- that searches through its children (<Route>
elements) to find the one whosepath
matches the current URL,Route
- to render some components when itspath
matches the current URL,Link
- to navigate through the routes.
By using the following code:
xxxxxxxxxx
1
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
In below example we create three pages handled by the react-router
:
Home
page,Gallery
page,About
page.
As we click on the different <Link>
components, the router renders the matching <Route>
components.
Simple routing example:
xxxxxxxxxx
1
import React from 'react';
2
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
3
4
// Pages ----------------------
5
6
const Home = () => {
7
return <h2>Home</h2>;
8
};
9
10
const Gallery = () => {
11
return <h2>Gallery</h2>;
12
};
13
14
const About = () => {
15
return <h2>About</h2>;
16
};
17
18
// Routing --------------------
19
20
const App = () => {
21
return (
22
<Router>
23
<div>
24
<div>
25
<Link to="/">Home</Link>
26
<Link to="/gallery">Gallery</Link>
27
<Link to="/about">About</Link>
28
</div>
29
<Switch>
30
<Route exact path="/">
31
<Home />
32
</Route>
33
<Route path="/about">
34
<About />
35
</Route>
36
<Route path="/gallery">
37
<Gallery />
38
</Route>
39
</Switch>
40
</div>
41
</Router>
42
);
43
};
44
45
export default App;