Search code examples
reactjslazy-loadingreact-suspense

React Suspense not working when fallback component is imported


I have made a LoaderPage component that looks like this

import theme from "../../assets/styles/globalStyles"
import Loader from "react-loader-spinner"
import React from "react"
import styled from "styled-components"

const Background = styled.div`
    display: "flex",
    align-items: "center",
    justify-content: "center",
    height: "100vh",
    background-color: ${theme.secondary}
`

export default function LoaderPage() {
    return (
        <Background>
            <Loader type="TailSpin" color={theme.primary} height={100} width={100} />
        </Background>
    )
}

I am trying to put this as the fallback component to my Suspense in my router component but the LoaderPage component doesn't show up before any other lazy-loaded component loads up

import React = require("react")
import { BrowserRouter as Router, Switch, Route, Redirect } from "react-router-dom"
const LoaderPage = import("../../pages/LoaderPage")
const LoginPage = React.lazy(() => import("../../pages/LoginPage"))

import PrivateRoute from "../Router/privateRoute"

export default function SNRoutes(): any {
    return (
        <Router>
            <React.Suspense fallback={LoaderPage}>
                <Switch>
                    <PrivateRoute exact path="/" component={LoginPage} />
                    <Route exact path="/login" component={LoginPage} />
                    <Redirect from="*" to="/" />
                </Switch>
            </React.Suspense>
        </Router>
    )
}

When I copy-paste the LoaderPage component and keep it in my Router component instead of importing it, it works though`.

Please help.


Solution

  • const LoaderPage = import("../../pages/LoaderPage") is a dynamic import which returns a Promise. The actual LoaderPage can be accessed with:

    let LoaderPage = null;
    const LoaderPagePromise = import("../../pages/LoaderPage");
    LoaderPagePromise.then(module => LoaderPage = module.default);
    

    This will not work as expected with <Suspense fallback={LoaderPage}>

    You should use this import instead:

    import LoaderPage from "../../pages/LoaderPage";