javascript – How to wait for a react component to RENDER? And while rendering display a loading screen?


I have a React application. It has a background video and 3 images which are used inside a form.

I want to wait for my route to fully render before showing it. While it renders, it should display a load screen.

My project until now:

I have tried to lazy load components, using this syntax with lazy loading:

const Component = lazy(() => import('./component/component'))

I also wrapped all my elements with the Suspense component

Code for illustrative purposes.


<Box overflow="hidden" >
      <Suspense fallback={<Loading/>}>
        <MainBackground />
        <ToastContainer />
        <Navbar />
        <Routes>
          <Route path="/x" element={<x />}></Route>
          <Route path="/x" element={<x />}></Route>
          <Route path="/x" element={<x />}></Route>
          <Route path="/x" element={<x />}></Route>
          <Route path="/x" element={<x />}></Route>
          <Route path="/x" element={<x />}></Route>
        </Routes>
        <Footer />
      </Suspense>
    </Box>

However, this didn’t work. It seems that lazy loading waits for the component to be loaded, but not for it to be rendered.

Also, I tried using useEffect on my components

const [loading, setLoading] = useState(true);

useEffect(() => {

   setLoading(false);
}, [])

So I could define when the component is rendered (As far as I have seen, people say this funcion is similar to ComponentDidMount and waits for the rendering of the component) or not.

However, it still wasn’t useful, when loading the page, I could see the Inputs being shown first, later, the background video, then the 3 images and last the paragraphs used.

What should I do?

Could the video/img props be the cause of this? What should I do?

Edit:

I verified that the issue might be on the images.

When testing the rendering time of the components, when the Loading ends, it seems that all the components are already rendered, however,their background images take time to be rendered/shown.

Explaning a little bit more:

I have a form component, which has 3 elements, and each one of them has a background image. I would like a way to wait those background images to be fully rendered on the component ‘-‘



Source link

Leave a Comment