S
S
sergmit2018-12-15 11:34:56
React
sergmit, 2018-12-15 11:34:56

How to implement architecture with lazy loading?

In the project I use lazy loading:

const Admin = React.lazy(() => import('./moduleAdmin/Index'))

class App extends React.Component {
  render () {
    const history = createBrowserHistory()
    return (
      <Router basename="/">
        <ConnectedRouter history={history}>
            <Suspense fallback={<Loader/>}>
              <Switch>
                <Route path="/admin" component={props => <Admin {...props} />}/>
                <Route path="/partner/:name" component={Partner}/>
                <Route
                  path="/"
                  component={() => <div>page not found</div>}
                />
              </Switch>
            </Suspense>
        </ConnectedRouter>
      </Router>
    )
  }
}

Tell me how to make the Admin module load only if the user is authorized

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-12-15
@sergmit

const AuthRoute = ({ component: Component, render, isSignedIn, ...rest }) => (
  <Route {...rest} render={props => {
    if (!isSignedIn) return (
      <Redirect to={{
        pathname: "/signin",
        state: { referrer: props.history.location.pathname }
      }} />
    );

    if (render) return render({ ...props });

    return <Component {...props} />;

  }} />
);

const mapStateToProps = state => ({
  isSignedIn: isSignedInSelector(state),
});

export default connect(mapStateToProps)(AuthRoute);

Well, a very simple solution without redirection:
<Switch>
  {isSignedIn && <Route path="/admin" component={Admin} />}
  <Route path="/partner/:name" component={Partner}/>
  <Route component={() => <div>page not found</div>} />
</Switch>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question