Ads Top

How to use lazy loading in react js?

 React lazy loading components:

In react we use lazy component with app routing. When load all component in the routing component then we use. When we import lazy component then need to call on the top as:

import { lazy, Suspense } from "react";

 

When we are importing our pages components then need to use with variable as:

const Home = lazy(() => import('./view/home'));

 

And then we need to call constant as:

<Switch>

                <Suspense fallback={<Preloader />}>

                    <Route path="/home" component={Home} />

                    <Redirect from="/*" to='/pagenotfound' />

                </Suspense>

            </Switch>

 

Also we create preloader component and it’s call to as a fallback method in Suspense component. You can create gif image or we can use loading css with animation Or we can type simple loading text in the Preloader components.

You can see below full example of the lazy component with react router:


Approuter.js

import { lazy, Suspense } from "react";

import { Switch, Route, Redirect } from "react-router";

 

/*import Home from './view/home';

import Grouppeoples from './view/grouppeoples';

import Services from './view/services';

import Pagenotfound from "./view/pagenotfound";*/

import Preloader from "./components/preloader/preloader";

 

const Home = lazy(() => import('./view/home'));

const Services = lazy(() => import('./view/services'));

const Pagenotfound = lazy(() => import('./view/pagenotfound'));

const strss = lazy(() => import('./view/story'));

const gallery = lazy(() => import('./view/gallery'));

const faq = lazy(() => import('./view/faqs'));

 

export default () => {

    return (

        <>

            <Switch>

                <Suspense fallback={<Preloader />}>

                    <Route path="/" exact component={Home} />

                    <Route path="/home" component={Home} />

                    <Route path="/services" component={Services} />

                    <Route path="/pagenotfound" component={Pagenotfound} />

                    <Route path="/departments" component={Departments} />

                    <Route path="/story" component={strss} />

                    <Route path="/gallery" component={gallery} />

                    <Route path="/faqs" component={faq} />

                    <Redirect from="/*" to='/pagenotfound' />

                </Suspense>

            </Switch>

        </>

    )

}

 

Preloader.js

export default () => {

    return (

        <>

            Loading...

        </>

    )

}

 

You can see below result:




No comments:

Copyright Reserved to Anything Learn. Powered by Blogger.