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.
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 whosepathmatches the current URL,Route- to render some components when itspathmatches 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:
Homepage,Gallerypage,Aboutpage.
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, Routes, 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>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/gallery" element={<Gallery />} />
</Routes>
</div>
</Router>
);
};
export default App;