Sergio Ivanuzzo
Sergio Ivanuzzo

Reputation: 1922

React + Redux best practice for router redirecting on redux state change

I'm using react-router-dom and I'm trying to bind it with redux. I want to redirect in action, but don't know, what the best way to do this. Am I need to using history.push() or something else? Maybe react has native approaches for this?

My code with Component container:

class ConnectedAppContent extends React.Component {
    render() {
        return (
            <div id="content">
                <Router>
                    <Switch>
                        <PropsRoute path="/login" component={LoginForm} doLogin={this.props.doLogin} />
                        <PrivateRoute path="/scan" redirectTo="/login" component={Scanner} token={this.props.token} />
                        <PrivateRoute path="/result" redirectTo="/login" component={ParsedQRCode} token={this.props.token} />
                    </Switch>
                </Router>
            </div>
        );
    }
}

const mapStateToProps = state => {
    return {
        token: state.token,
        parsedQRCode: state.parsedQRCode
    }
}

const mapDispatchToProps = dispatch => ({
    doLogin: token => dispatch(doLogin(token))
});

export const AppContent = connect(mapStateToProps, mapDispatchToProps)(ConnectedAppContent);

Upvotes: 1

Views: 1575

Answers (3)

MWO
MWO

Reputation: 2816

I would

import {Redirect} from 'react-router-dom';

and in the render method you can:

  render() {

    if (yourRedirectState) {
      return <Redirect to='/route'/>;
    }   
}

Upvotes: 2

Krina Soni
Krina Soni

Reputation: 930

If you want to route to particular path on some event as button click or submit, you can use Redirect or Link which are provided by react-router-dom.

Also, react-router works with redux , but in some cases it doesn't and you can wrap your component with the withRouter and then you can easily push the route with following:

history.push('/your-route')

Upvotes: 3

Dmitriy
Dmitriy

Reputation: 1241

I don't know of any other approaches but history.push() will work

const stateChange = () => {
  this.props.doLogin();
  this.props.history.push("/routetoredirect")
}

Upvotes: 1

Related Questions