Navigation 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.

In this tutorial, we will learn about the components that will help us in the navigation.

Single Page Apps

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 by downloading everything that’s needed to render the page the user requested. Then when the user navigates to a new page, asynchronous 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 want to be able to get back to a certain state using just the URL.

Why is this important? When you bookmark a site, that bookmark is only a URL, it doesn’t record the state of that page.

React Router

React Router turns React projects into single-page applications. It does this by providing a number of 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 and as it is open source 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

Browser Router work on the change in the URL. As the URL changes it respond and render the given instruction or pages. But for BrowserRouter to work we need to Wrap the whole App component inside the Browser router this itself is done in two ways, they both are one and same but it up to the person.

1)Either Wrap the app component inside the index.js in Browser Router

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

2)OR wrap every component in APP.js file inside the BrowserRouter

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

export default App;

Link Component 

In the React the anchor tag does not work to navigate to different pages of the web app. 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. Bypassing to Link’s property to the Link component, you tell your app which path to route to.

Syntax of link:-

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

If you’re experienced with routing on the web, you’ll know that sometimes our links need to be a little more complex than just a string. For example, you can pass along query parameters or link to specific parts of a page.

Route Component

Route is the main factor that recognizes the path and makes the routing possible. The route takes the path as 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 render function. This function will Load the component along with the Property.

Syntax:-

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

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

React-Router-Dom Example

  • Create a react app and clean the extra files
  • Create a components folder inside the src folder to store components files
  • Install react-router-dom package using the command
  • Create a Navbar.js file inside the components and requirements to react and Link from react-router-dom
  • Create a functional component named Navbar and use return with parenthesis.
  • Use <nav> tag to create a Navbar and inside it use h1 tag to create a heading of the site
  • Wrap that heading inside the Link and pass and attribute “to=” to navigate URL
  • Use unordered list and place to items AboutUs and ContactUs inside the link navigating to different pages.
  • And export this 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
  • Import react and fragment inside the file
  • Create an afunctional component and return JSX elements
  • Wrap inside fragment use different HTML tags to create an about us page
  • Use h1 for heading h2 for subheading and random paragraph
  • Export this component.

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 directory.
  • Import react and fragment inside the file
  • Create a functional component Contact and return JSX elements
  • Wrap everything inside the Fragment and use fieldset tag
  • Use legend tag to create heading of contact Details
  • Use <p> tags to provide details of contact and information
  • Export the component

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 components directory and import React
  • Use functional components and pass props as an argument
  • Use h1 tag to display Heading/home page and props to display name
  • 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 that use Fragment
  • Use The Navbar component at the top layer
  • Then use the Route but use it with render method as we need to pass props
  • And inside the Switch use the wrap the about us route and contact us route and pass their URL correctly
  • And export the App.js

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 from Navbar.