1

Using Create-react-app, I want to lazy load some of my components, this is working fine as long as the components are in the same folder as my main component (where I define the routes) however as soon as I want to load a component from another folder like

loader: () => import("../containers/HomeAContainer")

it fails to find/import the module. (exact same module will work if I move the file!

I have made a complete example which can be seen here

  • I have also tried to change the route to src/x/x instead of ../x/x but again getting errors.
Asha
  • 3,871
  • 7
  • 44
  • 57

2 Answers2

1

The way i create lazy loading components is through a higher order component. I create a file called "asyncComponent", then i put in the code:

import React, { Component } from 'react';

const asyncComponent = ( importComponent ) => {
    return class extends Component{
        state = { component: null }

        componentDidMount(){
            importComponent().then(cmp =>{
                this.setState({component: cmp.default});
            });
        }

        render (){
            const C = this.state.component;
            return C ? <C {...this.props} /> : null;
        }
    }
}

export default asyncComponent;

This component will receive a function as a parameter and then return the component you want. The function is actually a import funcion with the path of your component that you want to lazy load. So instead of using:

import Exemple from './example/example';

You will use:

import asyncComponent from './asyncComponent';
const asyncExample = asyncComponent(()=>{
    return import('./example/example');
});
Daniela Muniz
  • 123
  • 1
  • 10
  • Thanks for the reply, if you look at my approach in the sandbox it's very similar (a bit more dynamic) however the issue is with loading components where the file is located in another folder. – Asha Mar 22 '18 at 12:16
1

You are using a wrong path, correct it by using :

{ path: "/c", component: "./containers/HomeAContainer" }
Jouby
  • 2,196
  • 2
  • 21
  • 33
ProIt
  • 24
  • 2