The React Router

ahmedSoua
2 min readJun 11, 2021

--

Photo by Campaign Creators on Unsplash

When we build React apps for the web, we need to use a router to view the pages and navigate around them. Therefore, we are going to see the most popular router for React applications — React Router.

Install React Router

The first step to using React Router is to install the package. These are three different packages: React Router, React Router DOM, and React Router Native. The difference between them lies in their use. React Router DOM is for web apps and React Router Native is for mobile apps built with React Native.

npm install react-router-dom

React Router Setup

Once it’s installed we can bring our first component which is required to use the React router which is called BrowserRouter.

import { BrowserRouter as Router } from 'react-router-dom';

export default function App() {
return (
<Router>
{/* routes go here, as children */}
</Router>
);
}

Route Component

We declare the routes in the Router component as children and as many routes as we want and we need to provide at least two props for each route, path and component:

import { BrowserRouter as Router, Route } from 'react-router-dom';

export default function App() {
return (
<Router>
<Route path="/home" component={Home} />
</Router>
);
}

function Home() {
return <>home</>
}

Switch Component

Let’s say we have a route for the home page and the about page. Even though we specify two different paths, ‘/’ and ‘/ about’, when I visit the about page, we will see both the home and about components. We can solve this problem with the exact prop:

import {
BrowserRouter as Router,
Switch,
Route,
Redirect
} from "react-router-dom";

export default function App() {
return (
<Router>
<Switch>
<Route exact path="/" component={Home} />
<PrivateRoute path="/about" component={about} />
</Switch>
</Router>
);
}

function Home() {
return <>home</>;
}

function About() {
return <>about</>;
}

404 Route

If a user tries to navigate to a page for which we don’t have a route defined, we can create a route and then set the path to an asterisk *:

import { BrowserRouter as Router, Switch, Route } from "react-router-dom";

export default function App() {
return (
<Router>
<Navbar />
<Switch>
<Route path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="*" component={ErrorPage} />
</Switch>
</Router>
);
}

function ErrorPage() {
return <>404!</>;
}

--

--