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.

2 Answers 2

1

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

{ path: "/c", component: "./containers/HomeAContainer" }
Sign up to request clarification or add additional context in comments.

Comments

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');
});

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.