Share with   

How to route pages using react router in react application

In react js we can route pages or components using react router module.


Routing in React JS

Routing is the process for link the html pages and go to from one page to another page so we need routing in react js for Single Page Application.

 

Prerequisite

  1. Install Node JS
  2. Install React JS

 

Setup

Step 1

Install React Roter in your app

npm install react-router-dom --save

 

Step 2

Create component In react js app for writing route for pages. Component like Home, Contact US, About, Navbar, Router

 

Step 3

We have created navbar.jsx file for writting list of pages like home about and contact us pages

// src  > core-parts > navbar.jsx

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

class Navbar extends Component {
    render() {
        return (
            <ul>
                <li>
                    <Link to="/">Home</Link>
                </li>
                <li className="nav-item">
                    <Link to="/about">About</Link>
                </li>
                <li className="nav-item">
                    <Link to="/contact">Contact US</Link>
                </li>
            </ul>
        )
    }
}

export default Navbar

 

Step 4

Register this navbar component to routing page to allow to go to from one page to another page

// src > core-parts > router.jsx

import React, { Component } from 'react'
import {
    BrowserRouter as Router,
    Route,
} from "react-router-dom";
import Home from '../components/home';
import About from '../components/about';
import ContactUS from '../components/contactus';
import Navbar from './navbar';

class AppRoute extends Component {
    render() {
        return (
            <div>
                <Router>
                    <Navbar></Navbar>
                    <div>
                        <Route exact path="/" component={Home} />
                        <Route path="/about" component={About} />
                        <Route path="/contact" component={ContactUS} />
                    </div>
                </Router>
            </div>
        )
    }
}

export default AppRoute

 

Step 5

Finally in app.js use this AppRoute Component as rendering pages

import React from 'react';
import './App.css';
import AppRoute from './core-part/router';

function App() {
  return (
    <AppRoute></AppRoute>
  );
}

export default App;
Author Image
Guest User

0 Comments