i am new to React and have this route config in main.tsx (app generated by Nx):
ReactDOM.render(
<StrictMode>
<IocContainerProvider container={container}>
<Provider store={store}>
<BrowserRouter>
<Routes>
<Route path="//*" element={<App />}></Route>
{/* <Route path="/app/*" element={<App />}></Route> */}
<Route path="login" element={<Login />}></Route>
<Route path="*" element={<PageNotFound />} />
</Routes>
</BrowserRouter>
</Provider>
</IocContainerProvider>
</StrictMode>,
document.getElementById('root')
);
Then in the App-Component:
export function App() {
const navbarState = useSelector((state: AppState) => state.navbar);
return (
<>
<Sidebar></Sidebar>
<main className="main-content position-relative max-height-vh-100 h-100 border-radius-lg ">
<Navbar currentPageName={navbarState.currentPath}></Navbar>
<div className="container-fluid py-4">
<Routes>
<Route path="/" element={<Dashboard />} />
<Route path="/incomes" element={<Incomes />} />
<Route path="*" element={<PageNotFound />} />
</Routes>
<Footer></Footer>
</div>
</main>
</>
);
}
export default App;
Results using <Route path="//*" element={<App />}></Route>
:
- Navigating to Dashboard via : http://localhost:4200/ ==> works
- Navigating to Login via: http://localhost:4200/login ==> works
- Navigating to Incomes via: http://localhost:4200/incomes ==> PageNotFound
Results using <Route path="/app/*" element={<App />}></Route>
:
- Navigating to Dashboard via : http://localhost:4200/app ==> works
- Navigating to Login via: http://localhost:4200/login ==> works
- Navigating to Incomes via: http://localhost:4200/app/incomes ==> works
I dont want to use the '/app/*' prefix here in order to navigate to the 'incomes component'. How can i fix this?
CodePudding user response:
You don't have any nested route here. It is just different routes. I would recommend to group all of the route at the same place, so it is easier to understand your routing logic. And then, if you want to access the Incomes component with the path //incomes
, just add the route to the Routes component (in your index.js), like this:
<Routes>
<Route path="//*" element={<App />} />
<Route path="//incomes" element={<Incomes/>} />
<Route path="//login" element={<Login />} />
<Route path="*" element={<PageNotFound />} />
</Routes>
You could also look at the official documentation
Or, if you want to have nested routes, you have to add some Route to a Route component, like it is showed in this example. However, nested Route is for a different purpose, so you have to choose accordingly to your needs
<Routes>
<Route path="//" element={<App />}>
// This will be accessible through //incomes
<Route path="incomes" element={<Incomes/>} />
</Route>
<Route path="//login" element={<Login />} />
<Route path="*" element={<PageNotFound />} />
</Routes>