1

I'm using React Router in my React application, and I'm trying to set a default route within a nested route configuration. However, the default route doesn't seem to be working as expected.

I have the following route configuration in my App component:

import { BrowserRouter as Router, Routes, Route, Navigate } from "react-router-dom";
import AppLayout from "./pages/AppLayout";
import Home from "./pages/Home";
import Pricing from "./pages/Pricing";
import Product from "./pages/Product";
import CityList from "./components/CityList";
import SingleCity from "./components/SingleCity";
import CountryList from "./components/CountryList";
import Form from "./components/Form";

const App = () => {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="pricing" element={<Pricing />} />
        <Route path="product" element={<Product />} />
        <Route path="app" element={<AppLayout />}>
          <Route index element={<Navigate to="cities" replace />} />
          <Route path="cities" element={<CityList />} />
          <Route path="cities/:id" element={<SingleCity />} />
          <Route path="countries" element={<CountryList />} />
          <Route path="form" element={<Form />} />
        </Route>
      </Routes>
    </Router>
  );
};

export default App;

I want the default route within the "app" section to be "/app/cities". However, when I navigate to "/app" or any subpath under "/app" that doesn't match a specific route, it doesn't automatically navigate to "/app/cities" as I expect. Instead, it stays on "/app" without any changes.

The AppLayout component renders CityList and CountryList components. Here's the code for the AppLayout component:

import CityList from "../components/CityList"
import CountryList from "../components/CountryList"
const AppLayout = () => {
  return (
    <div>
      <CityList />
      <CountryList />
    </div>
  )
}

export default AppLayout

I have tried using the component as the default route, but it doesn't seem to work as intended. I'm not sure what I'm missing or if there is a different approach to achieve the desired behavior.

Sandro
  • 11
  • 2
  • What does `AppLayout` render? Can you [edit] to share that component code as part of your [mcve]? Can you also clarify how you are navigating around the app UI? – Drew Reese Jun 27 '23 at 19:21
  • I fixed it, instead of importing the CityList and CountryList in the AppLayout component, I import the Outlet from react-router. – Sandro Jun 27 '23 at 19:46

0 Answers0