I want to render a component based on an external condition, else redirect elsewhere in the app.
Ideally this redirection would be decided before the component, but in some cases I feel like I need to do this in the component. For example, in ReactRouter, the router might look like this:
<Router>
<Route path='/' component={LoadingPage} />
<Route path='/Home' component={HomePage} />
<Route path='/Login' component={LoginPage} />
</Router>
and the logic / sudocode for the LoadingPage will go something like this:
if (stillLoading) {
render
} else if (loggedIn) {
redirectToHome
} else {
redirectToLogin
}
It gets complicated, because sometimes the app is already loaded before the component is requested.
What lifecycle stage is the most appropriate place to put this redirection logic?
Each component in React has a lifecycle which you can monitor and manipulate during its three main phases. The three phases are: Mounting, Updating, and Unmounting.
The Redirect component was usually used in previous versions of the react-router-dom package to quickly do redirects by simply importing the component from react-router-dom and then making use of the component by providing the to prop, passing the page you desire to redirect to.
Two ways to handle redirecting on a user event such as create, update and delete with React Router.
I have a similar app, and I apply the flux pattern. I create a loginStore
to save the login status, and other pages watch it. I use higher order component to watch the store changes, so the loading status is passed into other components through props
. Then I do the page transition in UNSAFE_componentWillReceiveProps()
.
If you don't apply flux pattern, I think you have to decide how to know the external condition first. For example, put the logic in UNSAFE_componentWillReceiveProps()
if the external condition comes from props
.
Don't put the redirection logic in render which should be pure
. Every time when you invoke the render
method, it only returns the description of your DOM
instead of transition your page.
ComponentWillMount
also doesn't work. It's only invoked once and may be called before you login. GetInitialState
also has this problem, and it should only provide the initial state of your component.
I do redirect in componentDidMount
and have no issues with this, as I need redirects only during initial page load. I support other people in thinking that render
should remain pure, and always return valid DOM. If I know that I'll need to redirect, I just do return null;
from render
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With