Content

  • Routing in React
  • React Top Loading Bar
  • React Toastr (Toast Notifications)
  • Infinite Scroll in React

Routing in React

  • Routing allows navigation between different pages without reloading the browser.
  • React applications are Single Page Applications (SPA), so routing is handled on the client side using React Router.
  • React router enables page navigation

Important Components of React Router

Component Purpose
BrowserRouter Wraps the entire application and enables client-side routing.
Routes Acts as a container for all route definitions.
Route Maps a URL path to a specific component.
Link Used for navigation between routes without reloading the page.
NavLink Similar to Link but provides styling for the active route.

Example : Steps to implement routing in React

  • Install React Router using commnd
    npm install react-router-dom
  • Wrap App with BrowserRouter in main.jsx
    import { StrictMode } from 'react'
    import { createRoot } from 'react-dom/client'
    import './index.css'
    import App from './App.jsx'
    import 'bootstrap/dist/css/bootstrap.min.css'
    import { BrowserRouter } from 'react-router-dom'
    
    createRoot(document.getElementById('root')).render(
      <StrictMode>
        <BrowserRouter>
        <App />
        </BrowserRouter>
      </StrictMode>,
    )
  • Configure Routes in App.jsx
    import Header from "./components/Header";
    import Footer from "./components/Footer";
    import Home from "./components/Home";
    import About from "./components/About";
    import { Routes, Route } from "react-router-dom";
    
    function App() {
      return (
        <>
          <Header />
    
          <div className="container-fluid mt-4">
            <Routes>
              <Route path="/" element={<Home />} />
              <Route path="/about" element={<About />} />
            </Routes>
          </div>
    
          <Footer />
        </>
      );
    }
    
    export default App;
  • Update Navbar Links in Header component
    import { Link, NavLink } from "react-router-dom";
    function Header()
    {
        return(
            <>
                <nav className="navbar navbar-expand-lg navbar-dark bg-dark">
                    <div className="container">
    
                        <span className="navbar-brand">My React App</span>
    
                        <ul className="navbar-nav ms-auto">
                            <li className="nav-item">
                               <NavLink className="nav-link active" to="/" >Home</NavLink>
                              
                            </li>
    
                            <li className="nav-item">
                               <NavLink className="nav-link" to="/about">About</NavLink>
                            </li>
                        </ul>
    
                    </div>
                </nav>
            </>
        );
    }
    export default Header;
  • Run application and test routing

React Top Loading Bar

A top loading bar is a thin progress bar displayed at the top of the page. It visually indicates that some process is running in the background.

A top loading bar is commonly used when:

  • Page navigation happens
  • API calls are made
  • Data is loading or processing

Using a loading bar improves user experience by giving feedback instead of leaving the user waiting.


Steps to Add React Top Loading Bar

  • Install the loading bar package using npm:
    npm install react-top-loading-bar

Required React Hooks

The following React hooks are used:

  • useRef – To control the loading bar programmatically
  • useEffect – To trigger loading on route change
  • useLocation – To detect navigation changes

For documentattion Click here

Example: Loading Bar on Route Change

In this example, the loading bar appears automatically whenever the user navigates from one page to another (for example, Home → About).


import { Routes, Route, useLocation } from "react-router-dom";
import { useEffect, useRef } from "react";
import LoadingBar from "react-top-loading-bar";

import Header from "./components/Header";
import Footer from "./components/Footer";
import Home from "./components/Home";
import About from "./components/About";

function App() {
  const loadingRef = useRef(null);
  const location = useLocation();

  useEffect(() => {
    loadingRef.current.continuousStart();

    const timer = setTimeout(() => {
      loadingRef.current.complete();
    }, 800);

    return () => clearTimeout(timer);
  }, [location]);

  return (
    <>
      <LoadingBar
        color="#dc3545"
        height={4}
        shadow={true}
        ref={loadingRef}
      />

      <Header />

      <div className="container-fluid mt-4">
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/about" element={<About />} />
        </Routes>
      </div>

      <Footer />
    </>
  );
}

export default App;

Explanation of Important Parts

  • useRef is used to start and stop the loading bar without re-rendering the component.
  • useLocation detects when the URL changes during navigation.
  • useEffect runs every time the route changes and controls the loading bar.
  • continuousStart() starts the loading animation.
  • complete() finishes the loading animation.

Custom Loading Bar Options Used

  • color – Sets the bar color (red in this example)
  • height – Controls the thickness of the bar
  • shadow – Adds a shadow below the bar

Key Points

  • The loading bar works without page reload
  • It is suitable for navigation and API calls
  • The same logic can be reused in login and data-fetching screens

React Toastr (Toast Notifications)

Toastr is used to display non-blocking notification messages in a React application. It replaces traditional alert() with clean, professional UI messages.

Toastr is commonly used to show:

  • Success messages
  • Error messages
  • Warning alerts
  • Information notifications

Toastr improves user experience by providing instant feedback without interrupting the user.

Steps to Add Toastr in React

  • Install the toastr package using npm:
    npm install react-toastify

One-Time Toastr Configuration

The ToastContainer must be added once at the root level of the application (in App.jsx).


import { ToastContainer } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

Add ToastContainer inside the App.jsx:


<ToastContainer position="top-right" autoClose={3000} />

Using Toastr in Components

To show notifications, import the toast function in any component.


import { toast } from "react-toastify";

For documentattion Click here

Example

In this practical, we add buttons in the About component to test different toastr messages.

About.jsx


import { toast } from "react-toastify";

function About() {

  const showSuccess = () => {
    toast.success("Operation completed successfully!");
  };

  const showError = () => {
    toast.error("Something went wrong!");
  };

  const showInfo = () => {
    toast.info("This is an information message.");
  };

  const showWarning = () => {
    toast.warning("This is a warning message.");
  };

  return (
    <div className="container mt-4">
      <h2 className="text-success">About Page</h2>
      <p>This page demonstrates toastr notifications in React.</p>

      <button className="btn btn-success me-2" onClick={showSuccess}>
        Success
      </button>

      <button className="btn btn-danger me-2" onClick={showError}>
        Error
      </button>

      <button className="btn btn-info me-2" onClick={showInfo}>
        Info
      </button>

      <button className="btn btn-warning" onClick={showWarning}>
        Warning
      </button>
    </div>
  );
}

export default About;

Explanation of Important Parts

  • toast.success() – Displays a success notification.
  • toast.error() – Displays an error notification.
  • toast.info() – Displays an informational message.
  • toast.warning() – Displays a warning message.
  • ToastContainer – Responsible for rendering all toast messages.

Key Points

  • Toastr messages do not block the UI
  • Works perfectly with API responses
  • Can be reused for login success/failure
  • Improves overall application usability

Infinite Scroll in React

Infinite Scroll is a UI pattern where data loads gradually as the user scrolls

Example

  • Install infinite scroll using command :
    npm install react-infinite-scroll-component
  • Create Clients component and use infinite scroll
    import { useState } from "react";
    import InfiniteScroll from "react-infinite-scroll-component";
    
    function Clients()
    {
        const allClients = Array.from({ length: 50 }, (_, i) => ({
        id: i + 1,
        name: `Client ${i + 1}`,
        city: `City ${i + 1}`
      }));
    
      const [visibleClients, setVisibleClients] = useState(allClients.slice(0, 10));
    
      const fetchMoreData = () => {
        setTimeout(() => {
          setVisibleClients(prev =>
            allClients.slice(0, prev.length + 10)
          );
        }, 800);
      };
    
       return (
        <div className="container mt-4">
          <h2 className="text-primary mb-3">Clients List</h2>
    
          <InfiniteScroll
            dataLength={visibleClients.length}
            next={fetchMoreData}
            hasMore={visibleClients.length < allClients.length}
            loader={<h6>Loading more clients...</h6>}
          >
            <table className="table table-bordered">
              <thead className="table-dark">
                <tr>
                  <th>ID</th>
                  <th>Name</th>
                  <th>City</th>
                </tr>
              </thead>
              <tbody>
                {visibleClients.map(client => (
                  <tr key={client.id}>
                    <td>{client.id}</td>
                    <td>{client.name}</td>
                    <td>{client.city}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </InfiniteScroll>
        </div>
      );
    }
    export default Clients;
    • A new Clients component is created to display client records.
    • Sample data of 50 clients is generated using a JavaScript loop.
    • Initially, only a limited number of clients (10) are displayed on the screen.
    • The useState hook is used to store and manage the list of visible clients.
    • Client data is rendered using the map() function inside a Bootstrap table.
    • The react-infinite-scroll-component library listens to the page scroll event.
    • When the user scrolls near the bottom of the page, the fetchMoreData function is automatically called.
    • The fetchMoreData function loads the next set of clients and updates the state.
    • Updating state causes React to re-render the component with more client records.
    • Infinite scrolling continues until all 50 clients are loaded.
    • Once all clients are displayed, infinite scrolling stops automatically.
    • This approach improves performance by loading data gradually instead of all at once.
  • Add Route in App.jsx
    <Route path='/clients' element={<Clients></Clients>}></Route>
  • Add NavLink in Header component
     <li className="nav-item">
        <NavLink className="nav-link" to="/clients">Clients</NavLink>
     </li>
  • Run application and test infinite scroll