EN
React - route and link difference
3 points
In this article, we would like to show you the difference between Route and Link in React.
<Route>
is an element that renders some components when a current URL matches the route's path.<Link>
is an element used to navigate through routes.
In below example our App
component returns <Router>
which is the main component for our routing. Inside <Router>
we create ordered list containing <Link>
elements to the specific routes.
As we see <Link>
tags don't specify the content we want to display, they are used only to navigate through the routes. <Route>
element is the one that specifies the content which we want to display when <Link>
element's path
matches to it's path
.
Practical example:
xxxxxxxxxx
1
import React from 'react';
2
import { Route, Link, BrowserRouter as Router } from 'react-router-dom';
3
import Home from './Pages/Home.js';
4
import Page1 from './Pages/Page1.js';
5
6
const App = () => {
7
return (
8
<Router>
9
<div className="App">
10
<div className="App-menu">
11
<ol>
12
<li><Link to="/">Home</Link></li>
13
<li><Link to="/page1">Page 1</Link></li>
14
</ol>
15
</div>
16
<Route exact path='/' component={Home} />
17
<Route path='/page1' component={Page1} />
18
</div>
19
</Router>
20
);
21
};
22
23
export default App;
Notes:
- to use routing don't forget to install
react-router-dom
library first.
You can do this withnpm install react-router-dom
command.exact
property means the path necessary to display specific route component must be matched 1 to 1.