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

Handling Not Found Routes in React

Learn how to handle invalid URLs in React Router using wildcard routes. Create a custom 404 page, guide users back to valid pages, and improve navigation.

React Router 404 Page Practical Examples

01 What Is a Not Found Route?

A Not Found Route handles a URL that does not match any route defined in the application. For example, suppose an application contains Home, About, and Courses pages. If a user enters an invalid URL such as /unknown-page, no normal route matches it.

Instead of leaving the user with an empty page or confusing content, we can display a custom 404 page explaining that the requested page could not be found.

HOW A NOT FOUND ROUTE WORKS
User Opens a URL /unknown-page
↓
React Router Checks Routes Does any defined route match?
↓
No Matching Route Display the custom 404 page
Remember: A Not Found Route is a fallback route used when the URL does not match another route in the application's route configuration.

02 Why Do We Need a 404 Page?

Users can accidentally enter an incorrect URL, follow an outdated link, or request a page that is not available. A custom Not Found page helps them understand the problem and continue using the application.

  • It provides a clear message for invalid URLs.
  • It prevents users from seeing an unexpected blank page.
  • It can provide links back to valid pages.
  • It improves the application's navigation experience.
  • It keeps error handling consistent with the application's design.
Example 404 Page

404 - Page Not Found

Sorry, the page you are looking for does not exist.

Return to the Home page to continue browsing.

03 Understanding the Wildcard Route

React Router supports the wildcard path *. It matches URLs that are not matched by a more specific route in the current route configuration.

We can use this wildcard path to render a NotFound component. This component displays a message when a user visits an unknown URL.

Wildcard Route Syntax JSX
<Route path="*" element={<NotFound />} />

Explanation:

  • path="*" defines a wildcard route.
  • NotFound is the component displayed for an unmatched URL.
  • Place the wildcard route alongside the other routes in the relevant Routes configuration.
Important: The wildcard route is a fallback. React Router gives priority to more specific matching routes when selecting the route to render.

04 Create the NotFound Component

First, create a component named NotFound. It will display the 404 heading, a helpful message, and a link that allows the user to return to the Home page.

NotFound.jsx JSX
import { Link } from "react-router-dom";

function NotFound() {
    return (
        <div>
            <h1>404 - Page Not Found</h1>

            <p>
                Sorry, the page you are looking for
                does not exist.
            </p>

            <Link to="/">Go to Home</Link>
        </div>
    );
}

export default NotFound;

Code Explanation:

  • NotFound() defines the custom error page component.
  • The heading communicates that the requested page was not found.
  • The paragraph provides a helpful explanation to the user.
  • Link navigates back to the application's Home route.
Expected Browser Output

404 - Page Not Found

Sorry, the page you are looking for does not exist.

Go to Home

05 Configure the Not Found Route

Now define the normal application routes and add the wildcard route. In this example, the application contains Home, About, and Courses pages.

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

import Home from "./Home";
import About from "./About";
import Courses from "./Courses";
import NotFound from "./NotFound";

function App() {
    return (
        <BrowserRouter>
            <Routes>
                <Route
                    path="/"
                    element={<Home />}
                />

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

                <Route
                    path="/courses"
                    element={<Courses />}
                />

                <Route
                    path="*"
                    element={<NotFound />}
                />
            </Routes>
        </BrowserRouter>
    );
}

export default App;

How Does It Work?

  1. BrowserRouter: Enables browser-based routing.
  2. Routes: Groups the application's route definitions.
  3. Normal Routes: Define the Home, About, and Courses pages.
  4. Wildcard Route: Displays NotFound when no defined page route matches.
Note: The wildcard route belongs inside the same Routes configuration as the pages it should handle. For applications using nested routes, a wildcard may instead be placed inside a particular parent route when the fallback should apply only to that section.

06 Test Different URLs

After configuring the routes, test valid and invalid URLs to verify that the correct component appears.

URL: /

Home Page

Welcome to CIIT Training Institute.

URL: /about

About Page

Information about the application.

URL: /courses

Courses Page

Available courses are displayed here.

URL: /unknown-page

404 - Page Not Found

Sorry, the page you are looking for does not exist.

Go to Home

Expected behavior: Valid URLs render their corresponding components. An unmatched URL renders the NotFound component.

07 Improve the Not Found Page

A Not Found page can provide more useful navigation options. For example, it can display the application name and links to the Home and Courses pages.

NotFound.jsx JSX
import { Link } from "react-router-dom";

function NotFound() {
    return (
        <div>
            <h1>404 - Page Not Found</h1>

            <p>
                Welcome to CIIT Training Institute.
                The requested page could not be found.
            </p>

            <nav>
                <Link to="/">Home</Link>
                {" | "}
                <Link to="/courses">View Courses</Link>
            </nav>
        </div>
    );
}

export default NotFound;
Expected Browser Output

404 - Page Not Found

Welcome to CIIT Training Institute. The requested page could not be found.

Home | View Courses

The links use React Router's Link component so users can navigate to valid application routes without a full-page reload.

08 Common Mistakes to Avoid

  • Forgetting to import the NotFound component.
  • Defining the wildcard route outside the relevant Routes component.
  • Using a URL that does not match the intended route path.
  • Forgetting to provide a navigation link on the error page.
  • Placing the wildcard fallback in the wrong nested route scope.
Remember: A client-side Not Found page is a UI fallback. It does not automatically configure your web server to return an HTTP 404 status code. Server configuration may be needed when a real HTTP 404 response is required.

09 Practice Tasks

Complete these tasks to practise handling Not Found routes.

Task 1: Create a Custom 404 Page

Create a NotFound component that displays "404 - Page Not Found" and a helpful message.

Task 2: Add a Wildcard Route

Configure a wildcard route to display the NotFound component for unmatched URLs.

Task 3: Add Navigation Links

Add links to Home and Courses on the Not Found page.

Task 4: Test Invalid URLs

Visit URLs such as /wrong-page and /student-details and verify that the custom 404 page appears.

Task 5: Test Nested Routing

Create a dashboard with child routes and decide how an unknown URL under the dashboard should be handled.

Summary

Not Found Routes handle URLs that do not match the defined routes in a React application. React Router supports the wildcard path "*" to render a custom NotFound component. A useful 404 page explains the problem and provides links to valid pages. Testing both valid and invalid URLs helps verify the routing configuration and improves the user's navigation experience at CIIT Training Institute.