0

I am trying to fix an issue in my app where I need to modify the URL when all route params are not entered in the URL by the user. This is what my router looks like:

<Switch>
    <Route path="/A" exact strict component={T3} />
    <Route path="/B" exact strict component={BestOf} />
    <Route path="/C/:id" component={Author} />
    <Route path="/D" exact strict component={About} />
    <Route path="/E" exact strict component={ContactUs} />
    <Route path="/F/:id/:subId" exact strict component={Careers} />
    <Redirect to="/"
</Switch>

What happens: If I enter in URL bar http://localhost:3000/F/1, the app redirects to /.

What I want: I want to change such URLs to http://localhost:3000/F/1/0

I tried to use another Switch inside Switch to handle this, but I am not getting desired results.

Any help would be appreciated. Thanks in advance.

Kapil Sharma
  • 111
  • 1
  • 14

1 Answers1

1

What would could do is to make the url params optional and in Careers component redirect to the valid default url

<Switch>
    <Route path="/A" exact strict component={T3} />
    <Route path="/B" exact strict component={BestOf} />
    <Route path="/C/:id" component={Author} />
    <Route path="/D" exact strict component={About} />
    <Route path="/E" exact strict component={ContactUs} />
    <Route path="/F/:id?/:subId?" exact strict component={Careers} />
    <Redirect to="/" />
</Switch>

now in Careers component render method

render() {
     const { match: { params }} = this.props;
     if (!params.id || !params.subId ) {
        return <Redirect to=`${match.url}/0/0` />
     }
     // rest code here
}
Shubham Khatri
  • 211,155
  • 45
  • 305
  • 318