How to get started with React Router

swapnadeepmohapatra

Swapnadeep Mohapatra

Posted on May 4, 2020

How to get started with React Router

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

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

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.

import React from "react"

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

export default App;
Enter fullscreen mode Exit fullscreen mode

Now let's add a new route

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

import React from "react"
import { BrowserRouter, Route } from "react-router-dom"
Enter fullscreen mode Exit fullscreen mode

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

const Home = () => {
    return (
        <div>
            <h1>Home Page</h1>
        </div>
    )
}
Enter fullscreen mode Exit fullscreen mode

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

import Home from "./home"
Enter fullscreen mode Exit fullscreen mode

Now it's time to create a route, for that we will be using from the react-router-dom. A 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.

const App = () => {
    return (
        <BrowserRouter>
            <Route path='/' exact component={Home} />
        </BrowserRouter>
    )
}
Enter fullscreen mode Exit fullscreen mode

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

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

import React from 'react';

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

export default About;
Enter fullscreen mode Exit fullscreen mode

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

The App.js will look something like this.

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;

Enter fullscreen mode Exit fullscreen mode

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

image4

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

import { BrowserRouter, Route, NavLink } from 'react-router-dom';
Enter fullscreen mode Exit fullscreen mode

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

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>
    );
};
Enter fullscreen mode Exit fullscreen mode

It will look something like this.

image5

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

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;

Enter fullscreen mode Exit fullscreen mode

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

image6

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!

💖 💪 🙅 🚩
swapnadeepmohapatra
Swapnadeep Mohapatra

Posted on May 4, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related