Master React From Scratch

Clear, practical, and structured React lessons designed for beginners and developers.

COURSE SYLLABUS
1. Introduction to React
Introduction to React What Is React? Features of React Advantages of React Limitations of React Uses of React React vs JavaScript React Architecture
2. React Getting Started
Getting Started Introduction Prerequisites Installing Node.js and npm Creating a React Project with Vite React Project Structure Running React Application Your First React Application
3. JSX
JSX Introduction What Is JSX? JavaScript Expressions JSX Attributes Rendering JSX Elements JSX Children React Fragments JSX Rules and Best Practices JSX vs HTML
4. React Components
Components Introduction Functional Components Class Components Component Composition Reusable Components Component Tree Component Lifecycle Import and Export Components
5. React Props
Props Introduction What Are Props? Passing Props to Components Props Destructuring Default Props Values Children Props Typing Props with TypeScript Props vs State
6. React State
State Introduction What Is State? useState Hook Updating State Functional State Updates State with Objects State with Arrays State Immutability Lifting State Up
7. React Events
Events Introduction Handling Events Passing Arguments to Event Handlers Synthetic Events Form Events Keyboard and Mouse Events Event Propagation
8. Conditional Rendering
Conditional Rendering Introduction If-Else Rendering Ternary Operator Logical AND Operator Element Variables Preventing Rendering Multiple Conditions Conditional CSS Classes
9. Lists and Keys
Lists and Keys Introduction Rendering Lists with map() Understanding Keys Choosing Unique Keys Lists of Objects Filtering Lists Sorting Lists Empty Lists and Conditional Rendering
10. React Forms
Forms Introduction Handling Forms Controlled Components Uncontrolled Components Handling Input Fields Checkboxes and Radio Buttons Select and Textarea Form Validation Form Submission
11. React Hooks
Hooks Introduction useState Hook useEffect Hook Effect Dependencies and Cleanup useRef Hook useReducer Hook useMemo Hook useCallback Hook Custom Hooks Rules of Hooks
12. React Context API
Context API Introduction createContext useContext Context Provider Reading Context Updating Context Using Multiple Contexts Context API vs Props Context API Best Practices
13. React Routing
Routing Introduction Introduction to React Router Installing React Router BrowserRouter Setup Routes and Route Components Link and NavLink Programmatic Navigation URL Parameters and useParams Nested Routes Not Found Routes Protected Routes
14. API Integration
API Integration Introduction Fetch API Async/Await with API Calls Displaying API Data Loading and Error States Sending POST Requests API Error Handling Using Axios Custom Fetch Hook API Environment Variables
15. State Management
State Management Introduction Global State Prop Drilling Introduction to Redux Redux Core Concepts Redux Toolkit Store and Slices useSelector and useDispatch Async Operations with Redux Toolkit State Management Best Practices
16. React Performance
Performance Introduction Understanding Re-Renders Avoiding Unnecessary Re-Renders React.memo useMemo Optimization useCallback Optimization React Developer Tools and Profiler Lazy Loading Components Code Splitting Optimizing Large Lists Performance Best Practices

Protected Routes in React

In this lesson, you will learn how to create protected routes in React using React Router. Protected routes restrict access to specific pages based on conditions such as whether a user is logged in.

1. What Are Protected Routes?

A protected route is a route that allows access only when a particular condition is satisfied. For example, an application may allow only logged-in users to access a Dashboard page.

Consider an application with Login, Home, and Dashboard pages. Anyone can open the Home page, but the Dashboard page should be accessible only after login.

Real-Life Example

  • Home Page: Available to every visitor.
  • Login Page: Allows users to sign in.
  • Dashboard Page: Intended for authenticated users.
Important: Hiding or redirecting a page in React is not sufficient security by itself. Sensitive data and operations must also be protected by authentication and authorization on the server or API.

2. How Protected Routes Work

When a user tries to open a protected page, the application checks whether the user is logged in. If the condition is satisfied, the requested page is displayed. Otherwise, the user is redirected to the Login page.

User opens Dashboard
↓
Check login status
↓
Logged in?
Yes → Show Dashboard
Not logged in
→ Redirect to Login

This process provides a better user experience by directing users to the appropriate page according to their authentication status.

3. Import Required Components

React Router provides components such as Routes, Route, Navigate, and Link for managing application navigation.

The Navigate component can redirect a user to another route when a condition is not satisfied.

App.jsx — Imports
import {
    BrowserRouter,
    Routes,
    Route,
    Navigate,
    Link
} from "react-router-dom";

import { useState } from "react";
  • BrowserRouter enables browser-based routing.
  • Routes groups route definitions.
  • Route maps a URL to a component.
  • Navigate redirects users to another route.
  • useState stores the example login state.

4. Create the Login Page

First, create a Login component. For this learning example, a button changes the login state to true. In a real application, login status should be established only after the server successfully authenticates the user's credentials.

Login.jsx
function Login({ onLogin }) {
    return (
        <div>
            <h2>Login Page</h2>

            <p>Please log in to access your dashboard.</p>

            <button onClick={onLogin}>
                Login
            </button>
        </div>
    );
}

export default Login;

The onLogin prop receives a function from the parent component. When the user clicks the Login button, that function updates the login state.

This button is only a demonstration. It does not verify a username or password and must not be used as real authentication.

5. Create the Dashboard Page

The Dashboard component represents a page that should be available only after the user has logged in.

Dashboard.jsx
function Dashboard() {
    return (
        <div>
            <h2>Dashboard</h2>

            <p>Welcome! You have accessed the dashboard.</p>
        </div>
    );
}

export default Dashboard;

The Dashboard component contains the content that we want to show when the protected route's login condition is satisfied.

6. Create a Protected Route Component

We can create a reusable ProtectedRoute component. It receives the login status and the page that should be displayed.

If the user is logged in, the component renders its children. If the user is not logged in, it renders Navigate to redirect the user to the Login page.

ProtectedRoute.jsx
import { Navigate } from "react-router-dom";

function ProtectedRoute({ isLoggedIn, children }) {
    if (!isLoggedIn) {
        return <Navigate to="/login" replace />;
    }

    return children;
}

export default ProtectedRoute;

Understanding the Code

  • isLoggedIn indicates whether the user is logged in.
  • children represents the component placed inside the protected route.
  • if (!isLoggedIn) checks whether the user is not logged in.
  • Navigate redirects the user to the Login page.
  • replace replaces the current history entry instead of adding another one.
  • return children displays the requested page when the condition is satisfied.
Remember: The ! operator means NOT. Therefore, !isLoggedIn is true when isLoggedIn is false.

7. Configure the Protected Route

Now connect the Login, Home, and Dashboard components using React Router. The Dashboard route is wrapped inside ProtectedRoute.

App.jsx
import { useState } from "react";
import {
    BrowserRouter,
    Routes,
    Route,
    Link
} from "react-router-dom";

import Login from "./Login";
import Dashboard from "./Dashboard";
import ProtectedRoute from "./ProtectedRoute";

function Home() {
    return (
        <div>
            <h2>Home Page</h2>
            <p>Welcome to the application.</p>
        </div>
    );
}

function App() {
    const [isLoggedIn, setIsLoggedIn] = useState(false);

    const handleLogin = () => {
        setIsLoggedIn(true);
    };

    return (
        <BrowserRouter>
            <nav>
                <Link to="/">Home</Link>{" "}
                <Link to="/login">Login</Link>{" "}
                <Link to="/dashboard">Dashboard</Link>
            </nav>

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

                <Route
                    path="/login"
                    element={
                        <Login onLogin={handleLogin} />
                    }
                />

                <Route
                    path="/dashboard"
                    element={
                        <ProtectedRoute isLoggedIn={isLoggedIn}>
                            <Dashboard />
                        </ProtectedRoute>
                    }
                />
            </Routes>
        </BrowserRouter>
    );
}

export default App;

How It Works

  1. The initial login state is false, so the user is not logged in.
  2. The user opens /dashboard.
  3. ProtectedRoute checks the value of isLoggedIn.
  4. Because the value is false, the user is redirected to /login.
  5. Clicking the demonstration Login button changes the state to true.
  6. Opening /dashboard now displays the Dashboard.

8. Expected Output

Before Login

Login Page

Please log in to access your dashboard.

[ Login ]

If the user opens /dashboard before logging in, the application redirects to /login.

After Clicking Login

Dashboard

Welcome! You have accessed the dashboard.

The Dashboard can now be displayed because the example login state is true.

In this example, the login state exists only in React memory. Refreshing the page resets it to false. A real application needs a proper authentication mechanism and secure session management.

9. Common Mistakes

  • Forgetting the wrapper: If the Dashboard route is not wrapped in ProtectedRoute, the custom condition will not protect that route.
  • Using the wrong path: The redirect destination must match the configured Login route, such as /login.
  • Incorrect login condition: Check that the component redirects only when the user is not logged in.
  • Assuming client-side protection is enough: React routing does not replace server-side authorization.
  • Using a fake login in production: The sample button is for learning only and does not authenticate users.

10. Practice Tasks

Task 1: Protect a Profile Page

Create a Profile component and allow users to access it only when the login condition is true.

Task 2: Add a Logout Button

Add a Logout button that sets the demonstration login state back to false. After logout, opening the Dashboard should redirect the user to the Login page.

Task 3: Protect Multiple Routes

Protect both the Dashboard and Profile routes by reusing the same ProtectedRoute component.

Task 4: Display a Login Message

Update the Login page to display a message explaining that login is required before opening the Dashboard.

Summary

In this lesson, you learned how protected routes work in React Router, how to check a user's login state, how to create a reusable ProtectedRoute component, and how to redirect unauthenticated users with Navigate. You also learned how to protect Dashboard pages, understand common mistakes, and practise adding authentication-based navigation. Remember that client-side route protection improves navigation but real security must be enforced by the server or API. Congratulations on completing the React Routing lessons with CIIT Training Institute!