Getting Started With React Router
React is a front-end library developed by Facebook. It is used to build single-page applications. Which means all the components dynamic or static will be rendered inside one single html page. Nowadays, React is widely used to build single page applications. React Router does help us to render components conditionally in different routes of the application. Which makes our web app look like multiple page website.
Installing React Router
To install React Router, we need to go to the project directory and write the following command,
npm install react-router-dom
It will take some time to install react router to the app.
Then you will need to import react router to your app.
import React from ‘react’;
import {BrowserRouter as Router, Switch, Link, Route} from ‘react-router-dom’;
Router
The <Router> element wraps the component that has all the components. Everything that gets rendered will be wrapped inside <Router>. It is actually the <BrowserRouter> element, but we import it as the <Router> element.
Switch
The <Switch> element is like normal javascript “switch” statement. It tests different cases inside the element and renders component according to matched case.
Route
The <Route> element is used to render component based on a specific route.
Link
The <Link> element is like the html <a> tag. It navigates you to one route to another. You can use html <a> instead of <Link>.
The <Link> element takes you one route to another. And the <Route> element takes you to one component to another.
<Link> works based on <Route>’s path. It cannot work independently. Whereas, <Route>s can work without <Link>s.
A short example of react router,
function App(){
return(
<Router>
<Switch>
<Route exact path=”/”>
<Home/>
</Route>
<Route path=”/everything”>
<Everything/>
</Route>
</Switch>
</Router>
)
}
function Home(){
return(
<Link to=”https://www.google.com/”>Hello World</Link>
)
}
function Everything(){
return(
<Link to=”https://www.youtube.com/”>Everything’s gonna be all right</Link>
)
}
n.b — “<Route exact path=”/”>
<Home/>
</Route>”
This code renders a component that exactly matches with the path’s expression.
Conclusion
So, there you have it. You have got the basic idea of react-router. You can now easily navigate your react app with react-router. It is easy to use and it can make your react app feel like multi-page website.