Back to Debug Dungeon

The IonRouterOutlet Redirect Bug

12/19/2024

🐛 The Bug Hunt

You're building an Ionic React app and notice a weird bug: when users try to access a protected route without being logged in, the URL changes to /login but the dashboard page is still visible! The redirect seems to work in the address bar but not visually.

🔍 Spot the Bug in This Code:

import React from 'react';
import { Redirect, Route } from 'react-router-dom';
import { IonRouterOutlet } from '@ionic/react';

const AuthComponent = ({ isAuthenticated }) => {
  if (!isAuthenticated) {
    return <Redirect to="/login" />;
  }
  return <h1>Dashboard Content</h1>;
};

const AppRoutes = () => {
  const [isAuthenticated, setIsAuthenticated] = React.useState(false);

  return (
    <IonRouterOutlet>
      <Route path="/dashboard" exact>
        <AuthComponent isAuthenticated={isAuthenticated} />
      </Route>
      <Route path="/login" exact>
        <h1>Login Page</h1>
      </Route>
    </IonRouterOutlet>
  );
};

export default AppRoutes;

💡 Hints

🔧 Testing the Fix

To verify the fix works, toggle the isAuthenticated state and observe that:

  • The URL changes correctly
  • The page content updates to match the new route
  • Ionic's page transition animations work properly
  • The browser back/forward buttons behave correctly