React Routing: Practical Steps in Creating Navigation Bar that Renders Dynamic Content.

React Routing: Practical Steps in Creating Navigation Bar that Renders Dynamic Content.

A newbie in React will find it challenging in creating a navigation bar that renders different contents. Notable for building Single Page Applications (SPAs), React does not provide any modalities for routing. Nevertheless, routing in React is done using an external library known as React-router-dom. What this article aims to achieve is to create a Navigation bar with React. This Navigation bar will enable Users to navigate between internal links and renders different content.

To get a better understanding as we create our Navigation bar, this article will explain the following concepts:

  • React

  • SPAs

  • React Router Dom

  • Routing.

What is React?

React also known as ReactJS is a JavaScript library used in building interactive and dynamic web interfaces. In other words, React builds the front end of web pages that interacts with Users.

Although React was created as a Frontend library, over the years, React has evolved and can now be used to build complete applications. In general, React can be used to develop the following:

  • Single Page Applications (SPAs)

  • Backend server using frameworks such as Next.js, Gatsby.js, and so on

  • Mobile applications using React Native.

What are Single Page Applications (SPAs)?

SPAs are websites that render different content based on user requests without loading a new page. For instance, the default website loads an entirely new page when a user clicks a navigation link leading to other pages of the website. SPAs work in contrast to the default websites. SPAs load different web content on a single static page.

What Is React-router?

React-router is an external library that enables React apps to navigate between links and render different contents based on user requests. React router must be installed before it can be used in React.

What Is Routing?

Routing is the act of navigating to different sites, contents or pages using links based on user request. Through routing, a user can access different content on the websites.

Practical Steps in Creating Navigation Bar that Renders Dynamic Content.

In this section, we shall be building a React navigation bar that contains links rendering different contents based on user requests.

Note: To create a React app using React official doc recommendation, you must install Node.js and NPM on your computer. Visit https://nodejs.org to download Node.js and NPM if you don't have them on your computer.

Prerequisite: To have the best out of this article, it is important to be knowledgeable in JavaScript and React library tools such as Object, Object Destructuring, JSX, Components, and Variables, amongst others. If you are unfamiliar with the above tools, I recommend taking some time to learn and get familiar with them. Ready to learn? Let's get started.

Step 1 - Create A React App.

To create a React app, follow the below instructions:

  1. Create a folder for your React project.

  2. Navigate to the directory of the folder on your terminal to create a react app.

  3. Use npx or npm or yarn to create your react app as seen in the codes below.

C:\Users\Username\Desktop>mkdir react-app
C:\Users\Username\Desktop>cd react-app
C:\Users\Username\Desktop\react-app>npx create-react-app my-app

OR

C:\Users\Username\Desktop\react-app>npm init react-app my-app

OR

C:\Users\Username\Desktop\react-app>Yarn create-react-app my-app

Take note of the following:

  • react-app is the folder name and it can be any name of your choice.

  • my-app is the name of your React app and it can be any name of your choice.

Step 2 - Install react-router-dom and run Server.

Follow the below instructions to install react-router-dom and run sever.

  1. Navigate to your React app directory.

  2. Install react-router-dom using npm.

  3. Start the server using npm after react-router-dom has finished installing.

See the codes below.

C:\Users\Username\Desktop\react-app>cd my-app
C:\Users\Username\Desktop\react-app\my-app>npm install react-router-dom
C:\Users\Username\Desktop\react-app\my-app>npm start

The development server runs some scripts and then your default browser opens on localhost:3000 and displays the image below.

Step 3 - Modify Index.js File.

In this step, we shall begin coding our program as we have already created our app with all necessary installations. The below instructions guide us to modify the index.js file.

  1. Open your project folder with any code editor of your choice.

  2. Open the index.js file in your src directory.

  3. Import BrowserRouter from react-router-dom.

  4. Update root const by wrapping the app component in between BrowerRouter tags.

Our final codes will look just as in the example below.

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import { BrowserRouter } from 'react-router-dom';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>
);

Step 4 - Create Pages.

In this step, we shall be creating different pages with different contents. The following instructions guide us to create the necessary pages.

Firstly, create a folder called pages in the src directory with the following files:

  • Home.js

  • About.js

  • Contact.js.

Next, fill each of these files with their dynamic contents as seen below.

  • Home.js
function Home(){

    return (
        <>
          <h1>Home Page</h1>
        </>
    );
}

export default Home;
  • About.js
function About(){

    return (
        <>
          <h1>About Page</h1>
        </>
    );
}

export default About;
  • Contact.js
function Contact(){

    return (
        <>
          <h1>Contact Page</h1>
        </>
    );
}

export default Contact;

Step 5 - Create a Navigation Component.

Next, we shall be creating a navigation component. Follow the below instructions.

  1. Create a folder called 'components' in the src directory.

  2. Create a Nav.js file in the components' directory.

  3. Open Nav.js file you just created and import the Link from react-router-dom using object destructuring.

  4. Create a Nav function that returns a nav element with a class–nav.

See the codes below.

import { Link } from "react-router-dom";

function Nav(){
    return (
        <>
          <nav className="nav">
            <Link to="/">Home</Link>
            <Link to="/about">About</Link>
            <Link to="/contact">Book</Link>
          </nav>
        </>
    );
}

export default Nav;

In our above codes, in between nav tags, we have three Link elements. The Link elements will display as links on our browser and will be used to navigate between pages. The Link opening tags accept a 'to' attribute that points to the resources it's linking to.

Step 6 - Modify the App.js file.

Open the App.js file in the src directory and execute the following instructions:

  1. Import all pages files from the pages folder.

  2. Import the Nav component from the components folder.

  3. Import Routes and Route from react-router-dom using object destructuring.

  4. Render the Nav component at the return method of the App function.

  5. Create a Routes element containing three Route elements.

  6. Input each Route element with a path and element attributes.

Our final codes should be like the example below.

import React from 'react';
import './App.css';
import Home from './pages/Home';
import About from './pages/About';
import Contact from './pages/Contact';
import Nav from './components/Nav';
import { Routes, Route } from 'react-router-dom';

function App() {
  return (
    <div className="App">
      <Nav />

      <Routes>
        <Route path='/' element={<Home />}></Route>
        <Route path='/about' element={<About />}></Route>
        <Route path='/contact' element={<Contact />}></Route>
      </Routes>
    </div>
  );
}

export default App;

In our above codes, the path attributes indicate the URL route. The forward slash of the Home component signifies the default route. The element attributes accept the components to be rendered, which we imported earlier.

Step 7 - Style the Navigation bar.

Add CSS styles to our nav component. This can be done in the index.css file. See the codes below.

.navbar{
  background-color: rgb(14, 136, 207);
  padding: 3px;
  display: flex;
  justify-content: center;
  gap: 20px;
}

.navbar a{
  text-decoration: none;
  color: white;
  font-size: 1.3rem;
}

.navbar a:hover{
  color: aqua;
}

Note: we use the 'a' element selector when styling our Link element. This is because Link elements are anchor tags but with slightly different functionality.

Save your codes and navigate to your browser. Just as in the video below, we can now navigate between links and render different content.

In conclusion, we've created a React app with a navigation bar that enables us to navigate between links. All thanks to React-router-dom. This is not the end of React-router-dom. There are many uses of React-router-dom. Explore more and gain more experience using React-router-dom in React apps.

I hope this article was helpful, if yes, hit the like button and follow me on Twitter and LinkedIn for more insightful tutorials and technical articles.