How to Navigate Page in ReactJS

Navigation is very important to learn as nowadays the routing and multi URL websites and web apps are being very popular. React-router-Dom helps us to navigate to different components by changing the URL to Navigate Page in ReactJS.

In this tutorial, we will learn about the ReactJS Components that will help us to navigate one page to another page in reactJS.

What is Single Page Applications

Single-page applications can work in different ways. One way a single-page app loads is by downloading the entire site’s contents all at once. This way, when you’re navigating around on the site, everything is already available to the browser, and it doesn’t need to refresh the page.

Another way single-page apps work is, it downloads everything that’s needed to render the page the user requested. When the user navigates to a new page, JavaScript requests are made for just the content that was requested.

Another key factor in a good single-page app is that the URL controls the page content. Single-page applications are highly interactive, and users are able to get back to a certain page just by changing the URL that doesn’t render the whole website, only the page content.

Why Single page application is important? When a user wants to go to another page that page will render its content as well as it will refresh the whole site. It is time-consuming and less user-friendly. But with the SPA, it only renders the website once but changes its page contents based on what the user has selected, and based on that it updates the content of that page.

What is React Router

React Router turns React projects into single-page applications. It does this by,

  • providing specialized components (that manage the creation of links),
  • manage the app’s URL, 
  • provide transitions when navigating between different URL locations, and so much more.

It is an open-source package available on the node package manager. The current stable version of  5.2.0. We can freely use it in any commercial and production-based web app. And even we can contribute to their package if interested

Github:-https://github.com/ReactTraining/react-router

Install command 

PS D:\work\Codebun\React\first_app> npm i react-router-dom

The Major Factor of React Router Dom are

  1. BrowserRouter
  2. Link
  3. Route

BrowserRouter in ReactJS

Browser Router work on the change in the URL. As the URL changes it responds and renders the given pages (components). But for BrowserRouter to work we need to wrap the whole App component inside the <BrowserRouter>.

This can be done in two ways,

1)Either Wrap the app component inside the index.js in <BrowserRouter>

ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.getElementById('root')
);

2)Or wrap every component in the APP.js file inside the<BrowserRouter>

function App() {  
  return (
<BrowserRouter>
    <Router>
      <Fragment>
    
    <Navbar />
    <Route exact path ="/" component={landing} />
    </Fragment>
    </Router>
</BrowserRouter>
  )
  
};

export default App;

Link in ReactJs

In React the anchor tag does not work to navigate to different pages of the web app. Well, it does. But normal anchor tag will render the whole site. Hence we use the Link component from React Router Dom.

As you’ve seen, Link is a straightforward way to provide declarative, accessible navigation around your application. Pass a to attribute to the link that act like an href in an anchor tag. But instead of an URL address, we pass a pathname as a value to this to attribute.

Syntax of link:-

<Link to="/about">About</Link>

We can add query parameters as well to the Link if requires.

Route in ReactJS

The route is the main factor that recognizes the path and makes the routing possible. The route takes the path as an attribute/property and loads the component that is passed in the component attribute.

Syntax:-

<Route exact path ="/" component={Landing} />

To use the props /state to be passed inside the Route, we must use the render attribute and pass a callback function in it. This function will Load the component along with the Property.

Syntax:-

<Route exact path ="/" render={()=>(
      <Welcome name="CODEDEC" />
    )} />

In this example, we have created a basic web app that can handle the routes

How to Navigate Page in ReactJS

  • Create a react app
  • Create a components folder inside the src folder to store the component files
  • Install the react-router-dom package using the command prompt
  • Create a Navbar.js file inside the components folder and import  Link from react-router-dom
import { Link } from "react-router-dom";
  • Create a functional component named Navbar and use return with parenthesis (it can be a <div> tag or an empty fragment).
  • Use <nav> tag to create a Navbar
  • Inside the <nav> tag, use the <h1> tag to create a heading for the site
  • Create a <Link> tag inside this <h1> tag and pass the to attribute and its value (in which path we want to render the component) to it.
  • Use an unordered list by adding a <ul> tag and place items About Us and Contactus inside the link navigating to their specific pages (with the to attribute that we already declared).
  • And export this component so that this Navbar component can be usable from any other component.

Navbar.js

import React from 'react'
import {Link} from 'react-router-dom';

const Navbar = () => {
    return(
        <nav>
      <h1>
        <Link to="/"><i></i> Codedec</Link>
      </h1>
      <ul>
        <li><Link to="/aboutus">About Us</Link></li>
        <li><Link to="contactus">Contact</Link></li>
      </ul>
    </nav>   
    )
}

export default Navbar;
  • Create another file named About.js inside the components folder
  • Import react and fragment inside the file from ‘react’
import React, { Fragment } from "react";
  • Create a functional component and return JSX elements (<Fragment>)
  • Wrap every tag with this Fragment (use different HTML tags to create an about us page)
  • Use h1 tag for the heading h2 tag for the subheading and random paragraph
  • Export this component as well.

About.js

import React,{Fragment} from 'react';

const About = () =>{
    return (
    <Fragment>
        <h1>This Is CODEDEC</h1>
        <h2>An online platform for learning Trending Technologies from scratch</h2>
        <p> Random Key Strokes alsdujkf sfjkjdsfkjhsdf fhjsbadfsbd jfhasjd fhsbdjhabsjdfahsjd fjhshdfjsahd fjasdf asjhdfashbfdjasbd fjkdjfhbbasdhf s sdhfahsd
            dsfas dfiaushdkfhask sakdjfkajsdf  sdfhakjsd 
        </p>
    </Fragment>
    )
}

export default About;

  • Create one more file named Contact.js inside the components folder.
  • Import react and Fragment inside the file
import React, { Fragment } from "react";
  • Create a functional component named, Contact and return the Fragment
  • Wrap everything inside the Fragment and use the fieldset tag
  • Use legend tag to create heading of Contact Details
  • Use <p> tags to provide details of contact and information
  • Export the component too

Contact.js

import React,{Fragment} from 'react';
  
const Contact = () =>{
    return (
    <Fragment>
        <fieldset>
          <legend><strong>CONTACT DETAILS:</strong></legend>
          <p>Email:-help@codedec.com</p>  
          <p>Phone:-000000000000</p>  
          <p>Youtube:-random</p>  
          <p>Youtube:-random</p>  
        </fieldset>
    </Fragment>
    )
}

export default Contact;

  • Similarly, Create Welcome.js in the components directory and import React
import React from "react";
  • Create a functional component for the Welcome page just like the previous components, and pass props as an argument of this Welcome function
  • Use the h1 tag to display the Heading/home page and props.name to display the name (we will get the name from its parent component and this props will receive that thing as an object)

Note: read this article to know more about props.

  • Export these components

Welcome.js

import React from 'react';

function Welcome(props) {
    return(
    <h1>Welcome to {props.name}</h1>
    )
}

export default Welcome;

  • Now import Every component inside the App.js file
  • Also acquire BrowserRouter, Route, and Switch from react-router-dom
  • For Routes and links to work we need to Wrap everything inside BrowserRouter
  • Inside BrowserRouter, use Fragment to wrap the other JSX elements
  • Use The <Navbar > component at the top layer
  • Then use the Route but use it with the render method as we need to pass props
  • And inside the Switch wrap the About and Contact components as shown in the below code snippet. And pass their respective path as well.
  • And export the App.js (this should be exported by default. If not, export it manually)

App.js

import React, {Fragment} from 'react';
import {BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import './App.css';
import Navbar from './Components/Navbar';
import Header from './Components/Header';
import About from './Components/About';
import Contact from './Components/Contact';
import Welcome from './Components/Welcome';
function App() {  
  return (
    <Router>
      <Fragment>
    <Navbar />
    <Route exact path ="/" render={()=>(
      <Welcome name="CODEDEC" />
    )} />
    <Switch>
      <Route exact path="/aboutus" component={About} />
      <Route exact path="/contactus" component={Contact} />
    </Switch>
    </Fragment>
    </Router>
  )
  
};

export default App;

Now we can navigate to the About us page and contact us page by clicking on About Us and Contact. And the page won’t reload because it is a single-page web application. And this is how we can navigate pages with the help of react-router-dom in react.