JD. JD. - 1 year ago 145
React JSX Question

How to use React Router's redirect function?

I want to set it up so that if a condition is met the user is not allowed to enter this state he is redirected to another. Following the documentation here shows that it is possible, but doesn't include how it's done. Anyone have insight on this?

type EnterHook = (nextState: RouterState, replaceState: RedirectFunction, callback?: Function) => any;

type RedirectFunction = (state: ?LocationState, pathname: Pathname | Path, query: ?Query) => void;


Answer Source

There's a good example of how to use the onEnter hook in the auth-flow example. Here's the relevant code:

function requireAuth(nextState, replaceState) {
  if (!auth.loggedIn())
    replaceState({ nextPathname: nextState.location.pathname }, '/login')

  <Router history={history}>
    <Route path="/" component={App}>
      <Route path="login" component={Login} />
      <Route path="logout" component={Logout} />
      <Route path="about" component={About} />
      <Route path="dashboard" component={Dashboard} onEnter={requireAuth} />
), document.getElementById('example'))

As you can see, when the /dashboard route is accessed the requireAuth function is called. It receives two arguments: nextState, which is a RouterState object that represents the state the user is about to enter, and replaceState, a RedirectFunction that can be called to replace that state with something else. In this case, if the user isn't logged in, requireAuth calls replaceState like this:

replaceState({ nextPathname: nextState.location.pathname }, '/login')

The second argument is obviously the pathname the user will be redirected to. The first argument is an object that can contain any data we want the route handler (in this case the Login component) to have. Here the pathname the user was trying to go to (/dashboard) is set as the nextPathname property so after logging in the user can be redirected to that page (see the handleSubmit method in the Login component).

If the user is logged in, requireAuth does nothing, and since replaceState is never called the route works as usual, which is to say the Dashboard component is rendered.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download