writofmandamus
writofmandamus

Reputation: 1241

React Router - How to IndexRedirect to dynamic route

I have a situation in my React app to look like something as follows using react-router. I want the index of the users/:userId endpoint to redirect to another endpoint that includes a :userId params. What is a good way to do this? Right now the user from currentUser will return null because the code is only executed once in the beginning when the App is loaded the user is not yet authenticated. I'm guessing I will need to force react-router to reload the history and certain variables, or change the order of when I do authentication?

routes.js

{ /* Routes requiring login */ }
<Route onEnter={requireLogin}>
  <Route path="users" component={Users}>
    <Route path=":userId" component={User}>
      <IndexRedirect to={`/users/${currentUser().id}/profile`} />
      <Route path="profile" component={UserProfile} />
      <Route path="settings" component={UserSettings} />
      <Route path="activity" component={UserActivity} />
    </Route>
  </Route>
</Route>

Upvotes: 2

Views: 4594

Answers (1)

floriangosse
floriangosse

Reputation: 1123

If I understand it correctly and you want to redirect from /users/1 to /users/1/profile and /users/2 to /users/2/profile, you can simply replace ${currentUser().id} with :userId.

So your code would looks like this:

<Route onEnter={requireLogin}>
  <Route path="users" component={Users}>
    <Route path=":userId" component={User}>
      <IndexRedirect to="profile" />
      <Route path="profile" component={UserProfile} />
      <Route path="settings" component={UserSettings} />
      <Route path="activity" component={UserActivity} />
    </Route>
  </Route>
</Route>

Because the redirect is in the context of the route :userId: you can simply define your target route relative.

Upvotes: 3

Related Questions