DEV Community

EidorianAvi
EidorianAvi

Posted on

React: Router Setup

Today I'd like to do a quick breakdown of how to create a router in a React Project. When I was first getting into React I maintained it as a single page application without a router. How you ask? By managing all of my components via state and toggling them on and off as the user navigated the page. While it worked there was a lot of switches to keep track of and I had to create a lot of toggle functions to make sure the proper components were appearing at once. Not only that but since I was managing all my components via togglers I had to make sure none of them interfered with each other and it really reduced my ability to create custom page components. In short, it wasn't ideal.

That's where the router comes in.

The react router allows for client side routing. As we know routing can generally be done through the server via requests. However react projects being single page applications the react router is actually able to do all in site routing without having to make a request to the server.

Adding a router to your react project produces cleaner overall architecture and allows for setting your page components up in a much more modular fashion. It also saves you the headache of keeping track of what's toggled on and off. I'll be doing a demonstration of how to set up a basic router that allows for clean site navigation. Let's get started.

Setting it up

First things first lets install the router into our project:

npm install react-router-dom
Enter fullscreen mode Exit fullscreen mode

Great. now that we have that installed lets import parts of it into our App.js. Specifically the BrowserRouter and the Route.

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

Now for our walkthrough I will be using very generic names as I'm not creating an actual project I'm simply showcasing how to set up in an app router.

I created a folder in my src and I named it components. I then created four files inside the components folder, one for each component we will be creating and named them page1.js, page2,js, page3.js, and page4.js. Each component looks like this with different names of course:

import React from 'react'

const pageOne = () => {
    return (
        <div>
            <h1>Page One</h1>
        </div>
    )
}

export default pageOne;
Enter fullscreen mode Exit fullscreen mode

All they will be doing is returning an H1 element with the name of the page so we know which page we're on.

Now we have all of our generic pages we would route to. In an actual app you can build these up to be full fledged pages. Now make sure to import all four of these into our App.js that we will be routing from.

Lets now create a navigation bar for the application now. In the components folder I made a new file called NavBar.js

import React from 'react';

const Navbar = () => {
    return (
        <nav>
            <ul>
                <li><a href='/'>Page One</a></li>
                <li><a href='/page-two'>Page Two</a></li>
                <li><a href='/page-three'>Page Three</a></li>
                <li><a href='/page-four'>Page Four</a></li>
            </ul>
        </nav>
    )
}

export default Navbar;
Enter fullscreen mode Exit fullscreen mode

All it is a nav that houses hrefs to all of our pages. Notice I didn't make a custom href for Page One as that will be our home component that is displayed at first.

Now import that into your App.js

import Navbar from './components/Navbar.js';
Enter fullscreen mode Exit fullscreen mode

And bring it into the app and you will see an unordered list of links, one to each page.

Awesome we now have all the pieces we need to do some routing. We have a Navbar with links to each page, we have four separate pages, and we imported the BrowserRouter and the Route from our react-router-dom we're good to go.

First things first wrap your App in the Browser Router like so:

      <BrowserRouter>
        <div className="App">
        </div>
      </BrowserRouter>
Enter fullscreen mode Exit fullscreen mode

Now we will need the Navbar in every page for us to be able to use it for routing right? Go ahead and put that in your div.

        <div className="App">
          <Navbar />
        </div>
Enter fullscreen mode Exit fullscreen mode

Now we simply create a route for each page we want. A route will take in a path and the component it's routing to. So it will look like this.

<BrowserRouter>
   <div className="App">
      <Navbar />
      <Route exact path="/" component={pageOne}/>
      <Route path="/page-two" component={pageTwo}/>
      <Route path="/page-three" component={pageThree}/>
      <Route path="/page-four" component={pageFour}/>
   </div>
</BrowserRouter>
Enter fullscreen mode Exit fullscreen mode

You're all good to go. You can now click any of the links on your Navbar and it will route you to that component directly while maintaining access to the others through the navbar. One thing to notice is in my first route for pageOne I gave it an exact path. The reason being otherwise any path that included "/"
would get loaded on top of that path.

Anyways you could style up your Navbar as you see fit and then build out each of these pages to look how you want and now React can route between each page client side. Pretty neat right?

That'll be all from me today. I hope you're able to set up your very own react router moving forward. Thanks for checking this out and as always happy coding!

Top comments (2)

Collapse
 
enyichiaagu profile image
Amazing Enyichi Agu

Wow. Thanks for this blog post. It explains everything in simple terms.

Collapse
 
eidorianavi profile image
EidorianAvi

I'm happy it helped!