首页 > 解决方案 > How to conditionally route to a component in react based on a variable in the route?

问题描述

Here is an abstract of the what I am trying to imply:

Existing route <Route path="/public/reports/:reportid/page/:pageid" component={ PageComponent}/>

Idealist expectation of such a behaviour <Route path="/public/reports/:reportid/page/:pageid" component={ `:pageid` === -1 ? IndexPage : PageCompoennt }/>

To render a pdf in headless browser I have defined a public route, as an addition an index page was added recently, though I have this common route for individual page download, I wanted to reuse the same for index page ( index page doesnt have an identifier, so I thought maybe i'll filter out using -1 to be its index.. The above code is the somewhat the ideal case Im looking for.. Is there a way like this...?

标签: reactjsreact-router-dom

解决方案


您可以使用以下render道具Route

<Route 
    path="/public/reports/:reportid/page/:pageid" 
    render={(props) => 
        props.match.params.pageid === -1 ? 
            <IndexPage {...props} />: 
            <PageCompoennt {...props} />
    }
/>

推荐阅读