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.
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 whoseÂpath
 matches the current URL,Route
-Â to render some components when itsÂpath
 matches the current URL,Link
-Â to navigate through the routes.
By using the following code:
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:Â
import React from 'react';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
// Pages ----------------------
const Home = () => {
return <h2>Home</h2>;
};
const Gallery = () => {
return <h2>Gallery</h2>;
};
const About = () => {
return <h2>About</h2>;
};
// Routing --------------------
const App = () => {
return (
<Router>
<div>
<div>
<Link to="/">Home</Link>
<Link to="/gallery">Gallery</Link>
<Link to="/about">About</Link>
</div>
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/about">
<About />
</Route>
<Route path="/gallery">
<Gallery />
</Route>
</Switch>
</div>
</Router>
);
};
export default App;