johann
johann

Reputation: 1135

Route + Render + Redirect with react-router-dom

I just took over a React project from one of my colleague but I cannot understand the logic in the code below.

      content = <Switch>
        <Route path="/login" exact component={LoginPage} />
        <Route render={() => { return <Redirect to="/login" />; }} />
      </Switch>

I know how to use Route with Component, with Render, but Render with Redirect, first time I saw it.

Thanks

Upvotes: 0

Views: 2004

Answers (1)

Oliver Nicolaas Ponder
Oliver Nicolaas Ponder

Reputation: 929

This appears to be just another way of just saying:

<Redirect path='*' to='/login' />

Since it is inside a <Switch>, and after any <Route>, it will always match (if nothing above it got matched) and get rendered.

When the Redirect component gets rendered, it does its job of redirecting to the page specified in the to prop.

I found that out by doing some reading of the source code. If you're interested, there's a bit of indirection, but basically the Redirect component renders a Lifecycle component which will call method with the location provided as soon as it's mounted.

method is set like this:

const method = push ? history.push : history.replace;

And that's done like that because apparently the <Redirect> component can take push as a boolean prop, to set the behaviour of how the redirect is actually achieved.


Redirect component source https://github.com/ReactTraining/react-router/blob/master/packages/react-router/modules/Redirect.js

Lifecycle component source: https://github.com/ReactTraining/react-router/blob/master/packages/react-router/modules/Lifecycle.js

Upvotes: 1

Related Questions