3

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....

Raph117
  • 1,977
  • 3
  • 13
  • 29

2 Answers2

0

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

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

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;
Veno
  • 402
  • 2
  • 7
  • This is now working for me, and I have precisely 0 understanding of how, since it's what I did in the first place. Anyway thank you! – Raph117 Oct 01 '20 at 13:08
  • Go through this for more info [Reference](https://stackoverflow.com/questions/49162311/react-difference-between-route-exact-path-and-route-path) – Veno Oct 01 '20 at 13:09