EN
React / react-router 6 - basic routing example
13 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@6
with command line inside your project.
xxxxxxxxxx
1
npm install react-router-dom@6
Then you have to import:
BrowserRouter
(e.g. asRouter
) - that contains core routing logic,Routes
- 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, Routes, 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
<Routes>
30
<Route path="/" element={<Home />} />
31
<Route path="/about" element={<About />} />
32
<Route path="/gallery" element={<Gallery />} />
33
</Routes>
34
</div>
35
</Router>
36
);
37
};
38
39
export default App;