Skip to main content

Python print() Function

When you start learning Python, one of the first things you need to learn is how to display information on the screen. For example, you might want to display: A welcome message. Your name and age. The result of a mathematical calculation. Student marks and results. Information generated by a Python program. Python provides a built-in function called print() for displaying information. The print() function is one of the simplest and most frequently used functions in Python. It helps programmers display information while testing programs, solving problems, and developing applications. In this article, we will learn how to use print() with practical examples and their outputs. 1. What Is the print() Function in Python? The print() function is a built-in Python function that displays information in the output area, usually the terminal or console. Let's look at a simple example. print("Hello, World!") Output: Hello, World! In this example, Python displays the text Hello,...

React Router and Multi-Page Navigation in the PERN Stack

Introduction

In the previous article, we learned how to:

  • Connect React frontend with Express backend

  • Fetch API data

  • Use fetch() and Axios

  • Display database records

  • Handle forms

  • Perform CRUD operations

Now it is time to make our application look like a real-world website by adding:

  • Multiple pages

  • Navigation

  • Routing

  • Protected pages

This is done using:
React Router

In this article, we will learn:

  • What React Router is

  • Why routing is needed

  • Installing React Router

  • Creating pages

  • Navigation using Link

  • Dynamic routing

  • URL parameters

  • Protected routes

  • Frontend project structure


What is Routing?

Routing means:

Switching between different pages in an application

Examples:

  • Home page

  • About page

  • Login page

  • Dashboard page

Without routing, users cannot move between pages properly.


Traditional Routing vs React Routing

Traditional WebsiteReact Application
Entire page reloadsOnly UI changes
Slower navigationFaster navigation
Server handles pagesReact handles pages

What is React Router?

React Router is a library used for:

  • Navigation

  • URL management

  • Multi-page applications

It helps React applications behave like real websites.


Installing React Router

Open terminal inside client folder:

npm install react-router-dom

Understanding react-router-dom

The package:

react-router-dom

provides:

  • BrowserRouter

  • Routes

  • Route

  • Link

  • useNavigate

  • useParams

These help create navigation systems.


Basic Routing Structure

Inside:

src/App.js

add:

import {
    BrowserRouter,
    Routes,
    Route
} from 'react-router-dom';

function App() {

    return (

        <BrowserRouter>

            <Routes>

                <Route path="/" element={<h1>Home</h1>} />

                <Route path="/about" element={<h1>About</h1>} />

            </Routes>

        </BrowserRouter>
    );
}

export default App;

Understanding the Code

ComponentPurpose
BrowserRouterEnables routing
RoutesHolds all routes
RouteDefines page route

What is path?

path="/about"

defines URL path.

Example:

http://localhost:3000/about

What is element?

element={<About />}

defines which component should load.


Creating Separate Page Components

Inside:

src/pages

create files:

  • Home.js

  • About.js

  • Contact.js


Example Home Component

function Home() {

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

export default Home;

Example About Component

function About() {

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

export default About;

Updating App.js

import {
    BrowserRouter,
    Routes,
    Route
} from 'react-router-dom';

import Home from './pages/Home';
import About from './pages/About';

function App() {

    return (

        <BrowserRouter>

            <Routes>

                <Route path="/" element={<Home />} />

                <Route path="/about" element={<About />} />

            </Routes>

        </BrowserRouter>
    );
}

export default App;

Navigation Using Link

React Router provides:

<Link>

for navigation.


Why Link is Better Than anchor Tag

Wrong:

<a href="/about">About</a>

This reloads the page.

Correct:

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

This updates UI without reload.


Example Navbar

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

function Navbar() {

    return (

        <div>

            <Link to="/">Home</Link>

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

        </div>
    );
}

export default Navbar;

Adding Navbar to App

<>
    <Navbar />

    <Routes>

        <Route path="/" element={<Home />} />

        <Route path="/about" element={<About />} />

    </Routes>
</>

Dynamic Routing

Dynamic routing allows URLs like:

/students/1
/students/2
/students/3

Creating Dynamic Route

<Route
    path="/students/:id"
    element={<Student />}
/>

What is :id?

:id

is called a route parameter.

It changes dynamically based on URL.


Accessing Route Parameters

React Router provides:

useParams()

Example of useParams

import { useParams } from 'react-router-dom';

function Student() {

    const { id } = useParams();

    return <h1>Student ID: {id}</h1>;
}

export default Student;

Output Example

If URL is:

/students/5

Output:

Student ID: 5

Programmatic Navigation

React Router provides:

useNavigate()

for navigation using JavaScript.


Example of useNavigate

import { useNavigate } from 'react-router-dom';

function Login() {

    const navigate = useNavigate();

    const handleLogin = () => {

        navigate('/dashboard');
    };

    return (
        <button onClick={handleLogin}>
            Login
        </button>
    );
}

export default Login;

Protected Routes

Some pages should only be accessible after login.

Examples:

  • Dashboard

  • Profile

  • Admin panel

These are called:

Protected Routes

Simple Protected Route Example

function ProtectedRoute({ children }) {

    const isLoggedIn = true;

    if (!isLoggedIn) {

        return <h1>Access Denied</h1>;
    }

    return children;
}

Using Protected Route

<Route
    path="/dashboard"
    element={
        <ProtectedRoute>
            <Dashboard />
        </ProtectedRoute>
    }
/>

Nested Routing

Nested routes help create layouts like:

  • Dashboard sidebar

  • Admin panels

  • Settings pages


Example Nested Route

<Route path="/dashboard">

    <Route path="profile" element={<Profile />} />

    <Route path="settings" element={<Settings />} />

</Route>

React Frontend Folder Structure

Professional React structure:

src
│
├── components
├── pages
├── services
├── hooks
├── context
├── App.js
└── index.js

Understanding Each Folder

FolderPurpose
componentsReusable UI
pagesPage components
servicesAPI calls
hooksCustom hooks
contextGlobal state

Creating Reusable Components

Examples:

  • Navbar

  • Sidebar

  • Footer

  • Buttons

  • Cards

Reusable components reduce duplicate code.


Common Routing Mistakes

Forgetting BrowserRouter

Wrong:

<Routes>

Correct:

<BrowserRouter>

Using anchor Tags

Wrong:

<a href="/home">

Correct:

<Link to="/home">

Wrong Route Path

Wrong:

<Route path="about">

Correct:

<Route path="/about">

Real-World Applications of Routing

Routing is used in:

  • E-commerce websites

  • Student portals

  • Banking systems

  • SaaS dashboards

  • Social media platforms

Without routing, large applications become impossible to manage.


Best Practices

Keep Routes Organized

Use separate files for:

  • Public routes

  • Protected routes

  • Admin routes


Create Layout Components

Example:

  • MainLayout

  • DashboardLayout


Use Meaningful URLs

Good:

/students/5

Bad:

/page123

Lazy Load Components

Large applications should load pages only when needed.

This improves performance.


Conclusion

You have now learned how to build multi-page React applications using React Router.

You learned:

  • Routing

  • Navigation

  • Dynamic routes

  • Route parameters

  • Protected routes

  • useNavigate()

  • useParams()

  • Frontend structure

Now your React application is starting to look like a professional production-level application.

Comments

Popular posts from this blog

Understanding Comments in Java: A Beginner’s Guide

When learning Java programming, one of the first concepts you’ll come across is comments . Comments may not affect how a program runs, but they play a crucial role in making code more understandable, readable, and maintainable. Let’s dive deeper into what comments are, why they’re important, and the different types of comments in Java. What are Comments in Java? A comment in Java is a piece of text written within a program that is ignored by the compiler . In other words, comments are notes for humans, not instructions for machines. They help developers explain the purpose of code, describe logic, or temporarily disable certain lines of code without deleting them. Why are Comments Important? 📌 Readability – Comments make code easier to understand for you and others. 📌 Maintenance – When you revisit your code after months, comments remind you what you were doing. 📌 Collaboration – In team projects, comments explain code to fellow developers. 📌 Debugging – You c...

Java Program to Check Voting Eligibility

In this program, we’ll take the user’s age as input and check whether the person is eligible to vote or not. In India, the minimum age required to vote is 18 years . 💻 Program Code // Java Program to Check Voting Eligibility import java.util.Scanner; public class VotingEligibility { public static void main(String[] args) { // Create Scanner object to take input from user Scanner sc = new Scanner(System.in); // Ask user to enter age System.out.print("Enter your age: "); int age = sc.nextInt(); // Check eligibility if (age >= 18) { System.out.println("You are eligible to vote."); } else { System.out.println("You are not eligible to vote yet."); System.out.println("You can vote after " + (18 - age) + " year(s)."); } sc.close(); // Close the scanner } } 🧠 Explanation import java.util.Scanner; → Imp...

Java Program to Calculate Total Marks and Average of Five Subjects

💡 Program Explanation In this program: The user will input marks of five subjects . The program will calculate the total marks and average . It will then display both results clearly. 🧑‍💻 Java Code: // Java Program to Calculate Total Marks and Average of Five Subjects import java.util.Scanner; // Importing Scanner class for user input public class TotalAndAverage { public static void main(String[] args) { // Creating Scanner object to take input from user Scanner sc = new Scanner(System.in); // Declaring variables for five subjects double subject1, subject2, subject3, subject4, subject5; // Taking marks input for each subject System.out.print("Enter marks of Subject 1: "); subject1 = sc.nextDouble(); System.out.print("Enter marks of Subject 2: "); subject2 = sc.nextDouble(); System.out.print("Enter marks of Subject 3: "); subject3 = sc.nextDo...