Getting started with React Router
Tags: javascript, react, webdev
Published: 2022-07-20 21:08:28

- 
In this blog we are going to see the basics of React Router and get started with the first steps.

## The Basics

1. React Router is a client side library for React and React Native.

1. It makes navigating to different pages possible without needing a refresh.

1. Both declarative routing and imperative routing are supported.

## The First Use

We will be implementing the router in a new project and learn the concepts step by step.

- Install the router using the command
`$ npm install react-router-dom@6`
- Create two pages which will point to the two routes we are going to create.
```js
const FeedPage = () => {
  return <div>This page shows feeds.</div>;
};
export { FeedPage };
```
```js
const UserPage = () => {
  return <div>This page shows the details of a user.</div>;
};
export { UserPage };
```

- Import the BrowserRouter, Routes and Route from "react-router-dom". Wrap the whole project with `BrowserRouter`. This is necessary for react-router to work. Nest the `Routes` inside `BrowserRouter`. Now add a `Route` element for each route you want to specify.

```js
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import { FeedPage, UserPage } from "./pages";

import App from "./App";

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(
  <StrictMode>
    <BrowserRouter>
      <Routes>
        <Route path="feed" element={<FeedPage />} />
        <Route path="user" element={<UserPage />} />
      </Routes>
    </BrowserRouter>
  </StrictMode>
);

```
Here, `/feed` will point to `FeedPage` and `/user` will point to `UserPage` respectively. 

- We can now see that adding `feed` or `user` to the root `/` in the address bar takes us to the corresponding page.
![routing to feed](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fg44t9gmhl13iu43l1j1.png)

![routing to user](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ltu1menust5h94czik45.png)
  

- Voila! We just implemented the bare minimum react-router.

## Navigating using Links

Navigating to routes by changing the address manually is not very convenient, We will use now `Link` component to navigate to the desired page. 

- Create a `Homepage` where we will be adding two link components to navigate.
```js
<Route path="" element={<HomePage />} />
```

- Import and add two `Link` components into the `HomePage`
```js
import { Link } from "react-router-dom";

const HomePage = () => {
  return (
    <div>
      <div>
        <Link to="feed">Feed</Link>
      </div>
      <div>
        <Link to="user">User</Link>
      </div>
    </div>
  );
};
export { HomePage };
```
`Links` are similar to anchor tags but they do not lead to page refresh. Now clicking on the links take us to the corresponding page.

## The URL Params
Navigating to a route is good but what if we need to list a particular user using some identifier such as userId? 

- Edit the user route so that it takes in a userId as a parameter.
```js
<Route path="user/:userId" element={<UserPage />} />
```
- Edit the `Link` in HomePage to 
```js
<Link to={`/user/${123}`}>User</Link>
```
Here 123 is the parameter value passed to the user route. 
- We can read the passed param from the `UserPage` using `useParams()` hook as follows. Note that the param name which we used in `Route` component will be used to access the param from the UserPage.

We read the passed param as follows:
```js
import { useParams } from "react-router-dom";

const UserPage = () => {
  let params = useParams();
  return <div>This page shows the details of user {params.userId}.</div>;
};
export { UserPage };
```

- Now we can see that on clicking the Link on homepage we are successfully routed to the given userId.
![navigating to the userId](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v4prjd8fs0rrigdgngkv.png)
 
## The No Match Route
What if a user accidentally is routed to route which is not defined? For this purpose we can add a `Route` with '*' as path inside our `Routes`. This route will be matched when none of then path matches.
- Add a no match route as follows.
```js
<Route path="*" element={<div>Page not found!</div>}/>
```
- Now when we go a route which is not defined we will get a proper message that the page does not exists!
![no=match](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5c523yyqg1cxtthvb3i4.png)
 
## Navigating Programatically

Till now we have seen only one way of navigating to routes which is through `<Link>`. What if we need to navigate to a route after some action is performed such as button click or a page reload? We have `useNavigate()` hook which allows us to do that.

- Let's add a button to Homepage. On click of this button we will navigate to `FeedPage`.

```js
import { useNavigate } from "react-router-dom";

const HomePage = () => {
  let navigate = useNavigate();
  const buttonClickHandler = () => {
    navigate("feed");
  };
  return (
    <div>
      <button onClick={buttonClickHandler}>Feed Page</button>
```

- We can now see that on click of button we are successfully navigated to the `Feed` page.

## Demo
{% codesandbox https://codesandbox.io/embed/react-router-demo-nw2yof?fontsize=14&hidenavigation=1&theme=dark %}
## End
So this was all about the intro React Router. I hope it was beginner friendly to new users off React-Router. Please drop in your feedback or comments.

Have a good day!