How to get started with React Router
Tags: react, reactnative, javascript
Published: 2020-05-04 16:07:43

### What is React Router?

Before learning about React Router let's see whats react and why we need to use react-router?

## React

React is a JavaScript framework that is used to make SPAs (Single Page Application).

### Single Page Application (SPAs)

It's a website that has only one page. It re-renders its content in response to actions without refreshing the page. Simply, You don’t need to refresh the whole page when you click on any link.

### Why to use react-router?

As the page won't reload so how to change pages? So, here comes react-router which is used to move between different pages of the application without refreshing the page. 

_So, I hope now you know why we use react-router._

Let's now start by creating a react project and use react-router in that. 

Create a New React Application
==============================

Firstly create a new react application and call it routerapp. Run the command below in your command prompt/terminal/git bash.

`create-react-app routerapp`

Now, you will see a new folder created and inside the file, you can see something similar to this. 

![image1](https://firebasestorage.googleapis.com/v0/b/swapnadeep-blog.appspot.com/o/Annotation%202020-05-04%20201050.png?alt=media&token=12ccaade-8adf-4e5f-924f-059867408dc6)

Now navigate into the folder using the below command. 

`cd routerapp`

Install React Router Dom
======================

Now it's time to install the react-router-dom NPM package into the project. To do run the below command. 

`npm install react-router-dom`
or
`yarn add react-router-dom`

Let's run the app
==================
Now you can run the app using the below command.

`npm start`
or
`yarn start`

After a while, you can see the browser popping up and showing a site at `localhost:3000`

And it looks something like this.
![image2](https://res.cloudinary.com/practicaldev/image/fetch/s--0eTKEdkr--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://blog.crowdbotics.com/content/images/2019/05/ss1-1.png)

Open the project in Editor
========================== 

Open the project in your editor or IDE of your choice and open `app.js` from the `src` folder.

Now delete the previously written code and let's write it from the scratch.

```javascript
import React from "react"

const App = () => {
    return (
        <div>
           <h1>Hello World</h1>
        </div>
    )
}

export default App;
```

Now let's add a new route
==========================

To create the first route in our app, let us import `BrowserRouter` from `react-router-dom` library.

```javascript
import React from "react"
import { BrowserRouter, Route } from "react-router-dom"
```

Now create a new file named `home.js` and the home page should have a logic just like this. 

```javascript
const Home = () => {
    return (
        <div>
            <h1>Home Page</h1>
        </div>
    )
}
```

Now let's import the home page into our App.js

```javascript
import Home from "./home"
```

Now it's time to create a route, for that we will be using <Route> from the react-router-dom. A <Route> has a prop called path which is always matched with the location of the app. On the basis of this prop, the desired component gets rendered.

```javascript
const App = () => {
    return (
        <BrowserRouter>
            <Route path='/' exact component={Home} />
        </BrowserRouter>
    )
}
```

This will render the staring page as the home component. 

Now, if we visit the site we will see the Home component being rendered.

![image3](https://firebasestorage.googleapis.com/v0/b/swapnadeep-blog.appspot.com/o/Annotation%202020-05-04%20205244.png?alt=media&token=d6dc6ca3-579b-4fec-9b3a-0f122bfc3600)

Now let's add another as the second route and let's name it About.

```javascript
import React from 'react';

function About() {
	return (
		<div>
			<h1>About</h1>
		</div>
	);
}

export default About;
```

Now let's add this route to the App.js

The App.js will look something like this.

```javascript
import React from 'react';
import { BrowserRouter, Route } from 'react-router-dom';
import Home from './Home';
import About from './About';

const App = () => {
	return (
		<BrowserRouter>
			<Route path="/" exact component={Home} />
			<Route path="/about" exact component={About} />
		</BrowserRouter>
	);
};

export default App;

```

If we go to `localhost:3000/about`. We will something like this.

![image4](https://firebasestorage.googleapis.com/v0/b/swapnadeep-blog.appspot.com/o/Annotation%202020-05-04%20210056.png?alt=media&token=13ebdc86-c5f4-4f91-8f5f-4769c27c410e)

Add Navigation
==============

Now let's add a navbar so that we can easily navigate through these pages.

Firstly let's import `NavLink` from `react-router-dom`
```javascript
import { BrowserRouter, Route, NavLink } from 'react-router-dom';
```

Now let's wrap the routes inside a div and add a navbar on the top.

```javascript
const App = () => {
	return (
		<BrowserRouter>
			<div>
				<nav>
					<NavLink to="/">Home</NavLink>
					<NavLink to="/about">About</NavLink>
				</nav>
				<Route path="/" exact component={Home} />
				<Route path="/about" exact component={About} />
			</div>
		</BrowserRouter>
	);
};
```

It will look something like this. 

![image5](https://firebasestorage.googleapis.com/v0/b/swapnadeep-blog.appspot.com/o/Annotation%202020-05-04%20211532.png?alt=media&token=dd2a59e2-00bd-43e8-bc65-6a93d97ecd66)

You can add a bit of styling to make it look a bit beautiful.

```javascript
import React from 'react';
import { BrowserRouter, Route, NavLink } from 'react-router-dom';
import Home from './Home';
import About from './About';

const App = () => {
	return (
		<BrowserRouter>
			<div style={{ margin: 10 }}>
				<nav>
					<NavLink to="/" style={{ padding: 10 }}>
						Home
					</NavLink>

					<NavLink to="/about" style={{ padding: 10 }}>
						About
					</NavLink>
				</nav>
				<Route path="/" exact component={Home} />
				<Route path="/about" exact component={About} />
			</div>
		</BrowserRouter>
	);
};

export default App;

```

The app looks now a bit better. You can navigate between the pages by clicking on the links.

![image6](https://firebasestorage.googleapis.com/v0/b/swapnadeep-blog.appspot.com/o/Annotation%202020-05-04%20211532.png?alt=media&token=dd2a59e2-00bd-43e8-bc65-6a93d97ecd66)

The app is now completed. It's time for some theory.
===================================================

**exact**
This will make the path to match exactly to assigned value. For example, in about route, it will be matched on `/about` not `/about/me`

**path**
Inside the path, the path that will link to the component is assigned. For example, `/about` is assigned to go to the assigned component.

**component**
Here the component that is to be rendered is passed. For example, `About` is passed if the `About` component is to be rendered.

**to**
Here the path of the component that is to be rendered on click is passed. For example, `/about` is passed if on click of the NavLink, 'about' is to be rendered.

Conclusion
==========

We have seen how to get started with React Router and enable routing in a React SPA. 

I hope this helped you with understanding React Routing!
Thanks for reading!
**Happy Coding!**