0

In react-router v4 we now need to use a component to redirect the user to somewhere else.

While it makes sense when building the routes component (so a route can issue a redirection), it's very odd when, say, you have an error and must redirect somewhere, or redirect after a user action (that's not a simple link click).

Besides linking similar routes, redirections are also a reactive action, so why there's no API method for redirects, only a component?

igorsantos07
  • 4,456
  • 5
  • 43
  • 62
  • 2
    You can use `this.props.history.replace` or `this.props.history.push` if you want to redirect programmatically, [or create the `history` object yourself and use it programmatically wherever you like](https://stackoverflow.com/questions/50967404/change-route-from-store-in-react-application/50967604#50967604). – Tholle Aug 02 '18 at 15:11
  • Alright, this seems like a doc issue by the time I had this problem. Sorry for the dup ‍♂️ – igorsantos07 Jan 21 '19 at 20:02

1 Answers1

1

Well there are some cases where <Redirect /> is quite nice to use.

But, this is not a must.

There are many cases I created my "programmatically redirection" and you can use "history" that you get in props.

this.props.history.push('/dashboard')

if you don't have access to "history" in your props, as your component is not rendered inside the Route.

You can use the helper withRouter:

import {
  withRouter
} from 'react-router-dom'

and just wrap your component with it, and you will have the history accessable as a prop.

const yourComponent = props => {
    // this.props.history is here

    return <div> dont care </div>;
}
Tzook Bar Noy
  • 11,337
  • 14
  • 51
  • 82