Thursday, 16 June 2016

reactjs - Why do we need to render a component to issue a redirect in react-router?





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?


Answer



Well there are some cases where 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
dont care
;
}


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...