Miss. Tea
Miss. Tea

Reputation: 71

How to redirect to "/" if path is dynamic in Route React

<Router>
    <Switch>
        <Route
              exact
              path="/path1/"
              component={Page1} //(1)
            />

        {details && details.show_page && (
              <Route
                path={`/${details && details.page_url}`} //path2
                component={Page2}
              />
            )} //(2)
        <Redirect from="*" to="/" />
    </Switch>
</Router>

extra info: I am using Redux to get the value of path2, so I am checking its value inside the Router.(2)

Upvotes: 0

Views: 105

Answers (2)

palindrom
palindrom

Reputation: 19101

I think you should add this as the last route: <Route><Redirect to="/"/></Route>

<Router>
    <Switch>
        <Route
              exact
              path="/path1/"
              component={Page1} //(1)
            />

        {details && details.show_page && (
              <Route
                path={`/${details && details.page_url}`} //path2
                component={Page2}
              />
            )} //(2)
        <Route><Redirect to="/"/></Route>
    </Switch>
</Router>

Upvotes: 1

brff19
brff19

Reputation: 834

Try this... Typically redirects require an if/else condition to work properly.

<Router>
    <Switch>
        <Route
            exact
            path="/path1/"
            component={Page1}
        />

        {details && details.show_page ? (
            <Route
                path={`/${details && details.page_url}/`}
                component={Page2}
            />
        ) : <Redirect from="*" to="/" />
        }
    </Switch>
</Router>

Upvotes: 0

Related Questions