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:
import React from 'react';
import { Route, Link, BrowserRouter as Router } from 'react-router-dom';
import Home from './Pages/Home.js';
import Page1 from './Pages/Page1.js';
const App = () => {
return (
<Router>
<div className="App">
<div className="App-menu">
<ol>
<li><Link to="/">Home</Link></li>
<li><Link to="/page1">Page 1</Link></li>
</ol>
</div>
<Route exact path='/' component={Home} />
<Route path='/page1' component={Page1} />
</div>
</Router>
);
};
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.