Hackforge Academy

Category: react

React Router

Published on 04 Apr 2026

Explanation

Install React Router: First install react-router-dom package to enable routing in your React application.

Code:

npm install react-router-dom

Explanation

Main Routing Setup: Wrap your application inside BrowserRouter to enable routing across the app.

Code:

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { BrowserRouter } from "react-router-dom";

const root = ReactDOM.createRoot(document.
getElementById("root"));
root.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>
);

Explanation

Define Routes: Use Routes and Route components to map URLs to specific components.

Code:

import { Routes, Route } from 
"react-router-dom";
import Home from "./Home";
import About from "./About";

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

export default App;

Explanation

Navigation Between Pages: Use Link component instead of anchor tags to navigate without page reload.

Code:

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

function Navbar() {
  return (
    <nav>
      <Link to="/">Home</Link>
      <Link to="/about">About</Link>
    </nav>
  );
}

export default Navbar;

Explanation

Dynamic Route Parameters: Capture dynamic values from the URL using useParams hook.

Code:

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

function UserProfile() {
  const { id } = useParams();

  return <h2>User ID: {id}</h2>;
}

export default UserProfile;

Explanation

Programmatic Navigation: Use useNavigate hook to redirect users after an action like form submission.

Code:

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

function Login() {
  const navigate = useNavigate();

  const handleLogin = () => {
    navigate("/dashboard");
  };

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

export default Login;

Explanation

Protected Route Example: Restrict access to certain routes based on authentication status.

Code:

import { Navigate } from "react-router-dom";

function ProtectedRoute({ children }) {
  const isAuthenticated = true;

  if (!isAuthenticated) {
    return <Navigate to="/login" />;
  }

  return children;
}

export default ProtectedRoute;

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community