简体   繁体   中英

How to render a loading component with the useEffect hook?

I have a loading bar component which I can just import using this:

import { CircleToBlockLoading } from "react-loadingg";

and I am trying to use it like this which I am sure is incorrect as it renders nothing

useEffect(() => {
const timer = setTimeout(() => {
  return(
  <CircleToBlockLoading />
  )
}, 1000);
return () => clearTimeout(timer);

}, []);

Below are the links and documentation links for this external loading bar library:

This is the page for the live demos of several of these loading progress bar components

GitHub for these loading component bars

The loading bar library just lets you import the loading bar and use it as a component like:

<LoadingBar />

Essentially I am trying to load and show the progress loading bar as the page loads using useEffect hook and then I am trying for it to be hidden and render the rest of the page data. Below is my code at App level where I am trying to achieve this as at App level I render the navbar and the home page etc.

import "./App.css";
import React from "react";
import NavRouter from "./components/NavRouter";
import { CircleToBlockLoading } from "react-loadingg";
import { useRef, useEffect } from "react";


const App = () => {
const ref = useRef(null);
useEffect(() => {
const timer = setTimeout(() => {
  return(
  <CircleToBlockLoading />
  )
 }, 1000);
 return () => clearTimeout(timer);
 }, []);

return (
 <>
   {/* <CircleToBlockLoading /> */}
   <LoadingBar color="#0edaaf" ref={ref} />
   <NavRouter />
 </>
 );
};
// adding comment
 export default App;

Set a local state for tracking the loading. Based on that show the loader or content.

import "./styles.css";

// import "./App.css";
import React, { useState } from "react";
// import NavRouter from "./components/NavRouter";
import { CircleToBlockLoading } from "react-loadingg";
import { useRef, useEffect } from "react";

const App = () => {
  const ref = useRef(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const timer = setTimeout(() => {
      // return(
      // <CircleToBlockLoading />
      // )
      setLoading(false);
    }, 5000);
    return () => clearTimeout(timer);
  }, []);

  return (
    <>
      {(!loading && <div>MY CONTENT</div>) || (
        <CircleToBlockLoading color="#0edaaf" ref={ref} />
      )}
    </>
  );
};
// adding comment
export default App;

Let me know in case you have any doubts.

codesandbox - https://codesandbox.io/s/zealous-thunder-u2zj2?file=/src/App.js:0-730

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM