Home > Back-end >  Subroute with Variable Name in ReactJS Router
Subroute with Variable Name in ReactJS Router

Time:07-31

I'm a reactjs newbie, trying to figure out routing.

I'm using "react-router-dom" and I want to set up some links like this:

/p/<some id>
/p/<some id>/friends
/p/<some id>/pictures
/p/<some id>/otherstuff

With the below, I have the link "/p/" working, but "/p//friends", etc don't seem to work.

I have the following:

root.render(
    <React.StrictMode>
        <BrowserRouter>
            <Routes>
                <Route path="/" element={<App />} >
                <Route path="/p/:someId" element={<Profile />} >
                    <Route path="friends" element={<Friends />} />
                    <Route path="pictures" element={<Pictures />} />
                    ....
                </Route>
            </Routes>
        </BrowserRoute>
     <React.StrictMode>

)

My App.js

function App() {
    return (
        <div className="App">
            <Outlet />
        </div>
    );
} 

export default App; // nothing special

and Friends.js

const Friends = () => {
    return(
        <div className="App">
            <h1>Friends</h1>
        </div>
    )
}

export default Friends; // again, nothing special (the rest of the components are pretty much the same)

How can I get the above links to work?

Thanks!

CodePudding user response:

Route nesting not only nest the route paths, it also nest your components. Which means that for your route /p/:someId/friends, for example, your component tree will be:

<App>
  <Profile>
    <Friends />
  </Profile>
</App>

To render the nested routes, you need to add the <Outlet> component on <Profile> as well.

  • Related