Search code examples
javascripthtmlreactjsreact-routerurl-routing

Nested details route with react-router not rendering


I am using the react-router plugin to setup my routes I want to provide two routes list/ and list/:id (pretty common) What I have and what's working is this:

<Routes>
    <Route handler={App}>
        <Route name="list"
            handler={ListComponent}
            collection={new Collection()}>
        </Route>
    </Route>
</Routes>

But I am struggling to get my "details" route to work. What I tried is:

<Routes>
    <Route handler={App}>
        <Route name="list"
            handler={ListComponent}
            collection={new Collection()}>
            <Route name="list.details"
                path="list/:id"
                handler={DetailsComponent}>
        </Route>
    </Route>
</Routes>

First, this is not working currently, my DetailsComponent is not rendered when accessing list/123 (e.g.)

Second, even if this would work: how would I manager to pass one model in my collection "down" to the DetailsComponent?


Solution

  • To answer your first question, there are two issues with your router code. Coincidentally, a forward slash is the answer to both issues:

    1. You need to close all your Route components. If you write a <Route> by itself, you must include the closing tag like this: <Route/>.

    2. You likely need a forward slash at the start of your list path.

    So your code should look something like:

    <Routes>
        <Route handler={App}>
            <Route name="list"
                handler={ListComponent}
                collection={new Collection()}>
                <Route name="listDetails"
                    path="/list/:id"
                    handler={DetailsComponent}/>
            </Route>
        </Route>
    </Routes>
    

    Also, just to be clear, the route name is just a string identifier. I'm not sure if you wrote list.details as an object accessor to get to your model, but if so, it's not going to do what you think it will. I changed the name to listDetails to avoid any confusion, but list.details is also a valid string identifier so feel free to change it back if you'd like.

    That resolves the code issues in the block you provided here. Without seeing the DetailsComponent component and/or any error messages, I can't say for sure if there are any other issues.

    Regarding your second query, the solution is fairly straightforward (although react-router does not have the Backbone integration that you might be hoping for here). However, I'm afraid I'm only permitted to answer one question at a time according to StackOverflow rules. So I'd be happy to provide an answer if you create a separate question.