Nested Routes in React Router

Last Updated on April 11, 2022 by Pupli

Imagine we want to have the nested routing for User page via tabs.

function App() {
    return (
        <div>
            <Routes>
                <Route path="/" element={<Home/>}/>
                <Route path="/user" element={<User/>}>
                    <Route path="account" element={<Account/>}/>
                    <Route path="profile" element={<Profile/>}/>
                </Route>
            </Routes>
        </div>
    );
}
function User() {
    return (
        <div>
            <h1>User Page</h1>
            <Link to="profile">Profile</Link>
            <br/>
            <Link to="account">Account</Link>
            <Outlet/>
        </div>
    );
}

The Outlet component will always render the next match.
The parent route (User) persists while the swaps between the two child routes (Profile and Account).

References
https://reactrouter.com/docs/en/v6/getting-started/tutorial#nested-routes
https://reactrouter.com/docs/en/v6/getting-started/concepts#outlets
https://ui.dev/react-router-nested-routes
https://www.robinwieruch.de/react-router-nested-routes/