1

I'm trying to implement a private route with react-router v4 and redux, but the render prop returns null for some reason. I'd be very grateful if someone helps me figure out what is wrong. Router:

const router = (
          <Provider store={store}>
            <BrowserRouter history={history}>
              <App>
                <Route exact path="/" component={UserGrid}/>
                <Route path="/login" component={Login}/>
                <Route exact path="/users/:userId" component={UserPage}/>
                <Route path="/registration" component={RegistrationPage}/>
                <TopSecretRoute path="/topSecret" component={SecretComponent}/>
              </App>
            </BrowserRouter>
          </Provider>

TopSecretRoute.js:

const TopSecretRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={props => (
    props.session.registered ? (
      <Component {...props}/>
    ) : (
      <Redirect to={{
        pathname: '/login',
        state: { from: props.location }
      }}/>
    )
  )}/>
)

const stateToProps = ['session']
export default createContainer(stateToProps,TopSecretRoute)

enter image description here

Umbrella
  • 1,085
  • 1
  • 14
  • 30

2 Answers2

2

You are probably facing the problem React Router have with Update Blocking. This happens because Redux avoids re-renders and call mapStateToProps, instead.

To prevent this behavior your can pass the option pure: false in react-redux connect function.

Example:

connect(mapStateToProps, null, null, { pure: false })(Component);

You can head to React Redux API documentation to see more details on this option.

Andrey Luiz
  • 461
  • 9
  • 25
  • Thanks, didn't know about that, gonna read up on it later. I fixed the issue by removing TopSecretRoute component and encapsulating the behaviour I needed in a higher-order-component, which is also an option. – Umbrella May 07 '17 at 17:33
  • Yeah, there are more than one way to fix that. Glad it worked. – Andrey Luiz May 08 '17 at 22:22
0

As an alternate you can use withRouter

import { withRouter } from 'react-router-dom';
.
.
export default withRouter(connect(mapStateToProps)(AppRoutes));

References-

  1. https://github.com/ReactTraining/react-router/issues/4671
  2. https://reacttraining.com/react-router/web/api/withRouter
Varun Kumar
  • 2,543
  • 1
  • 23
  • 22