Home > Enterprise >  Handling optional Route path parameter (React)
Handling optional Route path parameter (React)

Time:04-14

Basically I have a login route where I wanna be able to declare an optional path parameter.

In my React Router, I have the following path for login:

<Route exact path={routingService.loginUrl(":returnUrl?")} render={Auth} />

Where routingService is declared like this:

const routingService = {
  loginUrl: (returnUrl?: string) => `/login/?${encodeURIComponent(returnUrl || "")}`,
};

I tried this way but it didn't work. It redirects me to the NotFound page instead.

<Route path="*" component={NotFound} />

But when I manually change the path to

<Route exact path="/login/:returnUrl?" render={Auth} />

...it does work, but I want to organize the path by using the one (loginUrl) we have in routingService.

This might be really simple to fix, but I'm kinda struggling. Any thoughts?

Thank you!

CodePudding user response:

Is that because of extra ? in the function?

Corrected one:

const routingService = {
  loginUrl: (returnUrl?: string) => `/login/${returnUrl || ""}`,
};

Edit:

encodeURIComponent(":returnUrl?") gives us ':returnUrl?', so it may not work. Maybe try without encodeURIComponent?

CodePudding user response:

I'm not sure why removing the extraneous "?" in the middle of the login path isn't working for you. The encodeURIComponent is certainly incorrect. You don't need to URLencode the paths you are trying to match by.

const routingService = {
  loginUrl: (returnUrl) => `/login/?${encodeURIComponent(returnUrl || "")}`,
};

console.log(routingService.loginUrl(":returnUrl?")); // "/login/?:returnUrl?"

Remove the extra question mark that is placing the returnURL in the queryString portion of the URL, and remove the encodeURIComponent function call, just return the returnUrl value.

const routingService = {
  loginUrl: (returnUrl) => `/login/${returnUrl || ""}`,
};

console.log(routingService.loginUrl(":returnUrl?")); // "/login/:returnUrl"

const routingService = {
  loginUrl: (returnUrl?: string) => `/login/${returnUrl || ""}`
};

...

<Switch>
  <Route
    exact
    path={routingService.loginUrl(":returnUrl?")}
    render={(props) => <Auth />}
  />
  <Route path="*" component={NotFound} />
</Switch>

Working sandbox demo

Edit handling-optional-route-path-parameter-react

  • Related