Understand React Router concepts by creating a simple react app

ericawanja

Ericawanja

Posted on November 10, 2021

Understand React Router concepts by creating a simple react app

Now that you have read the basics of react-router and why it is necessary let's get hands dirty by creating a simple app using the react-router library.
First things first, you need to create a react app. You can use the below command.
Secondly, install the react-router-Dom to make your app aware that you will be using this library.

yarn add react-router-dom       OR

npm install react-router-dom

Enter fullscreen mode Exit fullscreen mode

Next you need to delete all the unnecessary codes in your app. Basically, the index.html should look like this;

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />  
    <title>React App</title>
  </head>
  <body>
    <noscript> You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>

  </body>
</html>

Enter fullscreen mode Exit fullscreen mode

While the index.js on the src folder should look this.

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);
Enter fullscreen mode Exit fullscreen mode

Create the app frame

When building single-page applications, you must have a static part of the app that never changes. This unchanging section is known as the app frame. Our app frame will be a simple navigation bar and an empty section to display the requested components.
Inside the src folder, make the following changes in the app.js file.

import "./App.css";

function App() {
  return (
    <div className="App">
      <div className="navbar">
        <span>Home</span>
        <span> About</span>
        <span>Contact</span>
      </div>
      <div className="content"></div>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Copy the following styles to the app.css file

.navbar{
  display: flex;
  flex-direction: row;
  justify-content: center;
  font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;

}
span{
  padding: 10px;
  font-size: larger;
  font-weight: 600;
}

Enter fullscreen mode Exit fullscreen mode

Create the pages

Next, we need to create the components to be displayed. In our app, we need the home, about and contact components. In the src folder, create Home.js, Contact.js and About.js files and add the following codes
Home.js

import React from "react";

function Home() {
  return (
    <div>
      <h2>Home page</h2>
      <p>
        Duis aute irure dolor in reprehenderit in voluptate velit esse cillum
        dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
        proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
      </p>
    </div>
  );
}

export default Home;
Enter fullscreen mode Exit fullscreen mode

Contact.js

import React from 'react'

function Contact() {
    return (
        <div>
            <h1>Contact page</h1>
            <p>
            Lorem ipsum dolor sit amet, consectetur 
            adipiscing elit, 
            sed do eiusmod tempor incididunt ut labore et 
             dolore magna aliqua.
            Ut enim ad minim veniam, quis nostrud 
             exercitation ullamco laboris 
            nisi ut aliquip ex ea commodo consequat.
            </p>
        </div>
    )
}

export default Contact
Enter fullscreen mode Exit fullscreen mode

About.js

import React from 'react'

function About() {
    return (
        <div>
            <h2>About page</h2>
            <p>
            Ut enim ad minim veniam, quis nostrud exercitation 
            ullamco laboris nisi ut aliquip ex ea commodo consequat. 
            Duis aute irure dolor in reprehenderit in voluptate 
            velit esse cillum dolore eu fugiat nulla pariatur.
            </p>
        </div>
    )
}

export default About
Enter fullscreen mode Exit fullscreen mode

Add the routers

Now that we have installed the react-router library and built the app frame let's import the components that we will use. At the top level of the app.js, add the following statement.

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

Next, we need to define the routing region by enclosing the content in the browserRouter. The router should be wrapped inside the function.

import "./App.css";
import { BrowserRouter, Switch, Route,NavLink } from "react-router-dom";

function App() {
  return (
    <div className="App">
      <BrowserRouter>
      <div className="navbar">
        <span>Home</span>
        <span> About</span>
        <span>Contact</span>
      </div>
      <div className="content"></div>
      </BrowserRouter>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Add the navigation links

After defining the routing region, we will use the <NavLink> component to add the links. The navigation links have a to attribute which is used to specify the URL.

import "./App.css";
import { BrowserRouter, Switch, Route,NavLink } from "react-router-dom";

function App() {
  return (
    <div className="App">
      <BrowserRouter>
      <div className="navbar">
        <span><NavLink to= "/home">Home</NavLink></span>
        <span><NavLink to ="/about">About</NavLink></span>
        <span><NavLink to="/contact">Contact</NavLink></span>
      </div>
      <div className="content"></div>
      </BrowserRouter>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

On your terminal, enter npm start and click on the links. You will notice that the URL will change, but the respective pages are not displayed. To display them, you need to use the route matchers.

Add the routing matchers

The route matchers allow us to specify the component to be displayed when a certain URL is visited. Edit the App.js as follows and refresh the page.

import "./App.css";
import { BrowserRouter, Switch, Route, NavLink } from "react-router-dom";
import About from "./About";
import Contact from "./Contact";
import Home from "./Home";

function App() {
  return (
    <div className="App">
      <BrowserRouter>
      <div className="navbar">
        <span><NavLink to= "/home">Home</NavLink></span>
        <span><NavLink to ="/about">About</NavLink></span>
        <span><NavLink to="/contact">Contact</NavLink></span>
      </div>
      <div className="content">
        <Route path ='/home'><Home/></Route>
        <Route path ='/about'><About/></Route>
        <Route path ='/contact'><Contact/></Route>
      </div>
      </BrowserRouter>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Now when you try visiting each of the pages, their respective components will be displayed.
However, take a situation that you want the home page to be displayed every time the user visits the site. Then, it's to attribute on the link should be;
<span><NavLink to= "/">Home</NavLink></span>
While the path attribute on the component should look like this;
<Route path ='/'><Home/></Route>
If you refresh the page and click on the links, you will notice something is amiss. Can you guess it? The browser is displaying the Home component even when you visit the contact or the Home page. In most cases, you will not want that. That problem introduces us to the <Switch> tag.

When the <Switch> component is rendered, it searches through all its children to find a path which matches the URL and stops immediately after identifying the path. Unfortunately, if you place the home path first it will always match the URL which stops further search. Hence even when navigating to the about URL it will display the home page. What is the solution? The trick is to place the most specific URLโ€™S first. Thus our code at the content class should look like this;

     <div className="content">
          <Switch>
            <Route path="/about"> <About /></Route>
            <Route path="/contact"><Contact /></Route>
            <Route path="/"><Home /></Route>
          </Switch>
        </div>
Enter fullscreen mode Exit fullscreen mode

Another alternative is to use the exact prop which renders the URL only if the path exactly matches the current URL that is;
<Route exact path="/"><Home /></Route>

Final words

Learning to react-router doesn't end here, there is much more to learn. However, congratulations, now you have all the basics needed to use this library. You can check their official documentation for more.
At this point, I would appreciate it if you leave a comment down below.

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
ericawanja
Ericawanja

Posted on November 10, 2021

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

Sign up to receive the latest update from our blog.

Related

Features of Javascript You Should Know
javascript Features of Javascript You Should Know

October 17, 2024

Building 100% reusable UI kits
javascript Building 100% reusable UI kits

July 8, 2024

Splitting and Caching React Chunks
javascript Splitting and Caching React Chunks

December 30, 2023

ยฉ TheLazy.dev

About