Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In React is it always better to render a Redirect than use this.props.history.push?

If I'm always redirecting to in-app routes, what's the difference between the Redirect component in react-router-dom (v4), and this.props.history.push()?

E.g. let's say I want to add a user-given title to the URL and redirect from /foo/123 to /foo/123/some-title (both rendered with same Route/component).

I see in some uses of Redirect passing in state. Where does this end up?

Is it an anti-pattern to specify where you want to redirect to in the state? Why doesn't example code look like this:

save() {
  this.setState({ redir: '/new-path'; });
}
...
render () {
  if (this.state.redir) {
    return <Redirect to={this.state.redir} />;
  }
  ...
}
like image 248
Steve Clay Avatar asked Oct 15 '17 17:10

Steve Clay


1 Answers

I am someone who is sternly against rendering redirects as it is kind of counterintuitive that you have to render a component in order to change the page however it does provide some clear benefits

so the issue with this.props.history.push() is mostly when you are dealing with child components that are triggering redirects

Component A # the one Rendered by the Route
  Component B
    Component C # the one triggering the redirect

in the example above, unless you are diligent with passing down the route props from Component A down to Component C, then you wouldn't be able to use history.push() in Component C

Rendering Redirect was supposed to be the answer to that scenario that was provided by the maintainer of react-router but some people just dont like the idea at all(me included).


Functioanally speaking, there doesnt seem to be major differences in functionality between Redirect and history.push as Redirect uses it under the hood. The major reason to use Redirect over history.push is that Redirect is future proofed from possible changes on how history would work or if they decide to handle context differently at a later date.

like image 87
Maru Avatar answered Oct 23 '22 06:10

Maru