0
votes

Tried every possible solution available on the web. Please Help.

  1. Ran npm run eject
  2. Edited package.json file and tried the recommended solution of adding the below code as per https://reactrouter.com/web/guides/code-splitting.
  "babel": {
    "presets": [
      "@babel/preset-react"
    ],
    "plugins": [
      "@babel/plugin-syntax-dynamic-import"
    ]
  }

Below is my code where I use lazy loading. Only the root route ("/") gets loaded. Nothing is loaded when I visit localhost:3000/auth

enter image description here

import React, { useEffect, Suspense } from 'react';
import { connect } from 'react-redux';
import { Redirect, Route, Switch, withRouter } from 'react-router-dom';

import Layout from './components/Layout/Layout';
import Logout from './containers/Auth/Logout/Logout';
import BurgerBuilder from './containers/BurgerBuilder/BurgerBuilder';
import * as actions from './store/actions/index';

const Checkout = React.lazy(() => import('./containers/Checkout/Checkout'));
const Orders = React.lazy(() => import('./containers/Orders/Orders'));
const Auth = React.lazy(() => import('./containers/Auth/Auth'));

const App = (props) => {
  useEffect(() => {
    props.onTryAutoSignup();
  }, []);

  let routes = (
    <Switch>
      <Route
        path="/auth"
        render={(props) => {
          <Auth {...props} />;
        }}
      />
      <Route path="/" exact component={BurgerBuilder} />
      <Redirect to="/" />
    </Switch>
  );
  if (props.isAuthenticated) {
    routes = (
      <Switch>
        <Route path="/checkout" render={(props) => <Checkout {...props} />} />
        <Route path="/orders" render={(props) => <Orders {...props} />} />
        <Route path="/logout" component={Logout} />
        <Route path="/auth" render={(props) => <Auth {...props} />} />
        <Route path="/" exact component={BurgerBuilder} />
        <Redirect to="/" />
      </Switch>
    );
  }
  return (
    <div>
      <Layout>
        <Suspense fallback={<p>Loading...</p>}>{routes}</Suspense>
      </Layout>
    </div>
  );
};

const mapStateToProps = (state) => {
  return {
    isAuthenticated: state.auth.token !== null,
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    onTryAutoSignup: () => dispatch(actions.authCheckState()),
  };
};

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(App));

My package.json file package.json
My webpack config file webpack.config.js

1

1 Answers

0
votes

I have got my mistake. The webpack or babel config have nothing to do with lazy loading unless you are using Typescript which I'm not. I had a syntax error in my code which my IDE failed to recognise.

Instead of this

<Route
        path="/auth"
        render={(props) => {
          <Auth {...props} />;
        }}
 />
        

It should have been this

<Route path="/auth" render=(props) => <Auth {...props} /> />