Asha
Asha

Reputation: 4311

Lazy loading: react-loadable is failing to load components in other folders

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

Upvotes: 1

Views: 2022

Answers (2)

ProIt
ProIt

Reputation: 24

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

{ path: "/c", component: "./containers/HomeAContainer" }

Upvotes: 1

Daniela Muniz
Daniela Muniz

Reputation: 123

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

Upvotes: 1

Related Questions