How to default to a route based on a URL parameter

Viewed 97

I have a routing setup where if only 1 param is given, i.e /:id I want the router to always redirect to /:id/overview.

For example, if the user goes to /hello, I want them to be redirected to /hello/overview.

I've tried doing this like this:

<Switch>
  <Route exact path="/" component={NoParam} />
  <Redirect from="/:section" to="/:section/overview" />
  <Route exact path="/:section/:pageName" component={GeneralOverviewPage} />   
</Switch>

This causes an infinite re-render. I'm not sure how to achieve this redirect, and would really appreciate any help. Thanks.

EDIT=======

Now trying to do it like this:

const GeneralOverviewPage: FC<RouteComponentProps<GeneralOverviewPageProps>> = (
  props
) => {
  console.log(props);
  return !props.match.params.pageName ? (
    <Redirect to={props.match.params.section + '/overview'} />
  ) : (
    <h1>{props.match.params.pageName}</h1>
  );
};

export default GeneralOverviewPage;

and

<Route path="/:section" component={GeneralOverviewPage} />
      <Route path="/:section/:pageName" component={GeneralOverviewPage} />

This means that /hello is now redirecting to /hello/hello/overview....

2 Answers

Your <Redirect from="/:section" to="/:section/overview" /> must be inside GeneralOverviewPage component.

if(!pageName){
  return (<Redirect from="/:section" to="/:section/overview" />);
}

This will Help You around for understanding!

import React from 'react';
import { Switch, Route, Redirect } from 'react-router-dom'

const App = () => {

    return (
        <Switch>
            <Route exact path="/" render={
                () => console.log("Hi")
            } />
            <Redirect exact from="/:section" to="/:section/overview" render={
                () => console.log("Hi 1")
            } />
            <Route exact path="/:section/:pageName" render={
                () => console.log("Hi 2")
            } />
        </Switch>
    )
}

export default App;
Related