DEV Community

Cover image for Episode 5: Navigating the Routes with the Router Knights
vigneshiyergithub
vigneshiyergithub

Posted on • Edited on

Episode 5: Navigating the Routes with the Router Knights

Episode 5: Navigating the Routes with the Router Knights


The morning sun bathed Planet Codex in a warm glow, highlighting the intricate network of routes that connected its sectors. Arin was on her way to meet the legendary Router Knights, the defenders responsible for keeping the routes of information secure and efficient. These pathways formed the digital backbone of Planet Codex, guiding users through their journeys.

Arin arrived at the Router Hall, a massive structure with arching entryways that pulsed with a rhythmic light. The atmosphere hummed with an energy that mirrored the constant flow of data.

“Cadet Arin!” called Knight Linkus, captain of the Router Knights. His voice was firm, and his presence exuded confidence. “Are you ready to learn the art of navigation?”

Arin nodded, anticipation sparking in her eyes.


“Understanding the Routes: Structuring Navigation”

Knight Linkus led Arin to the grand map room of Router Hall, where the glowing paths were drawn across a digital map. “Routing, Cadet, is what guides users to their destinations,” he began. “Each route defines a specific path and ensures the correct view is displayed.”

He demonstrated how routes were structured:

import { createBrowserRouter, RouterProvider, Outlet } from 'react-router-dom';

function Products() {
  return (
    <div>
      <h1>Products</h1>
      <Outlet /> {/* Ensures child routes render correctly */}
    </div>
  );
}

const router = createBrowserRouter([
  { path: "/", element: <Home /> },
  { path: "/about", element: <About /> },
  {
    path: "/products",
    element: <Products />,
    children: [
      {
        path: "details/:productId",
        element: <ProductDetails />,
      },
      {
        path: "reviews",
        element: <ProductReviews />,
      },
    ],
  },
]);

function App() {
  return <RouterProvider router={router} />;
}
Enter fullscreen mode Exit fullscreen mode

“Nested routes ensure that /products/details/:productId or /products/reviews are displayed within the Products component, maintaining an organized and efficient structure,” Linkus explained.

Arin imagined how these nested routes would make navigation seamless, allowing users to explore related areas without leaving the main pathway.


“Defending with Protected Routes”

Knight Linkus then motioned to a section marked by secure paths. “Not all routes are accessible to everyone. Some must be protected to prevent unauthorized access.”

He explained how they managed these routes:

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

function ProtectedRoute({ element, isLoggedIn }) {
  return isLoggedIn ? element : <Navigate to="/login" />;
}

const router = createBrowserRouter([
  {
    path: "/dashboard",
    element: <ProtectedRoute element={<Dashboard />} isLoggedIn={userIsAuthenticated} />,
  },
]);
Enter fullscreen mode Exit fullscreen mode

“Protected routes safeguard our most critical areas,” he said, “ensuring only those with proper access can proceed.”


“Loaders: Preparing for the Journey”

Knight Linkus gestured to a glowing stream that represented preloaded data. “Before users arrive at their destinations, we must ensure that everything they need is ready. That’s the role of loaders.”

He illustrated their use:

const router = createBrowserRouter([
  {
    path: "/products",
    element: <Products />,
    loader: async () => {
      try {
        const response = await fetch('/api/products');
        if (!response.ok) {
          throw new Error('Data fetch failed');
        }
        return response.json();
      } catch (error) {
        console.error('Loader error:', error);
        return [];
      }
    },
  },
]);
Enter fullscreen mode Exit fullscreen mode

“Loaders act like scouts,” Linkus said. “They prepare the way so users never encounter an empty route.”


“Actions: Handling Changes in Real Time”

Finally, Knight Linkus pointed to pathways with a pulsing energy. “Sometimes, Cadet, routes must allow changes. That’s where actions come in.”

He showed an example:

const router = createBrowserRouter([
  {
    path: "/products/add",
    element: <AddProduct />,
    action: async ({ request }) => {
      try {
        const formData = await request.formData();
        const response = await fetch('/api/products', {
          method: 'POST',
          body: formData,
        });
        if (!response.ok) {
          throw new Error('Data submission failed');
        }
        return response.json();
      } catch (error) {
        console.error('Action error:', error);
        return { error: 'Submission failed' };
      }
    },
  },
]);
Enter fullscreen mode Exit fullscreen mode

“Actions enable us to respond to user inputs—like adding new data—directly within the routes, keeping Codex responsive,” Linkus said.


“Mastering the Routes”

As the session came to an end, Arin surveyed the glowing map, her mind racing with newfound understanding. Knight Linkus placed a reassuring hand on her shoulder.

“Today, you’ve learned how to structure, secure, and optimize routes. Remember, routes are more than pathways—they are the foundation of user journeys.”

With a determined nod, Arin left the Router Hall, ready to apply her new knowledge in the defense and development of Planet Codex.

Top comments (0)