octagonal
octagonal

Reputation: 91

Redirection from a query string to a path

I'm currently in the process of updating a legacy app's frontend which used query parameters as a "path". (Ex: ?greeting=hello instead of /greeting/hello)

However moving forward we want to transition to path-based routing, with redirection from the legacy query structure.

Preferably I would've liked to do something like this:

<Redirect from="?gameid=:game" to="/game/:game" />

However it doesn't seem to be as straightforward as that since react-router does not provide support for query params (#209).

What's the cleanest way to solve this?

URL manipulation with plain JS has been proven to be quite error-prone in combination with react.

Upvotes: 0

Views: 1303

Answers (1)

octagonal
octagonal

Reputation: 91

Turns out my situation was one that was quite an edge case and thus not handled well by react-router.

Since the app uses a hash-based history (/#/path), query parameters would simply not be catched if they weren't preceded by a hash in onEnter's nextState.

What I ended up doing was handling any possible queries inside of an IndexRouter.

<IndexRoute component={LoginPage}
  onEnter={
    (nextState, replaceWith) => {
      console.log(nextState);
      var obj = qs.parse(document.location.search.split("").slice(1,document.location.search.split("").length).join(""));
      if(obj.gameid){
        document.location.href = document.location.origin + document.location.pathname + "#/game/" + obj.gameid;
      }
    }
  }
/>

This way seems preferable to putting routing logic inside a container app's componentDidMount since routing logic actually belongs inside of a Route. It also ensures all subsequent calls will be handled properly.

Kudos to /u/mrkre for pointing me in the direction of onEnter.

Upvotes: 2

Related Questions