0

How to do a route redirect in React component with react router 3 ?

If I user a 'guard' component like this:

const GuardContainer = (props) => {

    const {ok} = isOk(props)

    if (!ok) {
        // Redirect here  to /not-ok      
        return null
    }

    return <WrappedComponent {...props}/>
}

then React complains about changing state with

Cannot update during an existing state transition (such as within render or another component's constructor).

2 Answers 2

2

In React Router V4 there is a <Redirect /> component that allows you to render and it will navigate to the target. You can probably make your own in V3 using browserHistory:

import React from 'react';
import { browserHistory } from 'react-router';

class Redirect extends React.Component {

  componentDidMount() {
    browserHistory.push(this.props.to);
  }

  render() {
    return <div />
  }

}

export default Redirect;

Then render it with to="/not-ok"

if (!ok) {
  return <Redirect to="/not-ok" />;
}

Give this a try or something similar to it.

Sign up to request clarification or add additional context in comments.

1 Comment

Dude - you just helped me out so much. I had been trying to find a solution for this for a long time. Thank you man
0

Decision from react-router v3:

    import React from 'react';
    import { browserHistory } from 'react-router';

    export default function GuardContainer(props) {
        const {ok} = isOk(props);

        if (!ok) {
            // Redirect here  to /not-ok
            browserHistory.push('/not-ok');
        }

        return <WrappedComponent {...props} />
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.