wlingke wlingke - 11 months ago 103
React JSX Question

Where to programatically re-route in React Router?

Suppose I have some component that is connected to react router and redux. I want the component to automatically re-direct to another route when the state "isLoggedIn" becomes false. This is what I have so far:

state => ({
isLoggedIn: selectors.getIsLoggedIn(state),
class AdminGate extends React.Component {
render() {
const { isLoggedIn, router, ...restProps } = this.props;
if (!isLoggedIn) {
return isLoggedIn ? <InnerComponent {...restProps} /> : <div>Prohibited</div>;

Current the below works but I see an error in the console:

warning.js:44 Warning: setState(...): Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`.

If I moved this logic to
, it obviously only runs once.

What is the right way to set something like this up? I understand I could possibly amend the
method to do the
but that doesn't feel ideal. I'd prefer the component to handle that based on the state.

Answer Source

I think you could try to use componentWillUpdate(nextProps, nextState) lifecycle method in order to see whether it's logged in or not.