Write asynccomponent in react router config for lazy loading

342 Views Asked by At

I'm new to react. Trying to lazy load the components. Am using server side rendering along with react router config. I need to lazy load the components.

asyncComponent.js

import React, { PureComponent } from 'react';

export default class  extends PureComponent {
 constructor(props) {
super(props);

this.state = {
  Component: null
}
}

componentWillMount() {
if(!this.state.Component) {
  this.props.moduleProvider().then( ({Component}) => this.setState({ Component }));
}
}

render() {
const { Component } = this.state;

//The magic happens here!
return (
  <div>
    {Component ? <Component /> : ''}
  </div>
);
 }
 };

Route.js

import React from 'react';
import App from './app';
import asyncComponent from './asyncComponent';

const Home = asyncComponent.moduleProvider(import('./components/Home'));

const routes = [{
    component: App,
    routes: [
        {
          path : '/',
          exact: true,
          component: Home
        }
    ]
}];

export default routes;

I have refered the example from [https://github.com/rubenspgcavalcante/react-webpack-lazy-loading.git][1]

This is throwing exception. Is this the correct way to do it?

0

There are 0 best solutions below