简体   繁体   中英

Show loading spinner until component has finished rendering

I have a slow rendering component, I wan't to be able to show a loading spinner until that component has mounted to the DOM.

The reason why this component is slow to render is trivial, it is a long list that can have many list elements. (react window / virtualization won't apply to this use case nor will pagination).

I have tried Suspense and lazy loading, though, that only starts rendering once the component has been imported. I've learned that this isn't what lazy loading is for.

Ideally, I'd like to start rendering the component straight away but hide it with display: none . (I don't even know if this is possible because it has to be mounted to have this css rule applied).

Is this a limitation of my slow-to-render component or is there a possible solution?

Thanks, and help is greatly appreciated!

I would figure you could just use ternary operators with setState. Default state should be false, then in the componentDidMount or useEffect of the Component that needs to load, setState to true. Then in the html implement the ternary operators based on that state rendering the loader while it's false:

   const [isLoaded, setIsLoaded] = useState<boolean>(false)
   
   useEffect(() => { setIsLoaded(isLoaded => true) },[])


    {
     isLoaded ?
     <TheComponent />
     :  
     <div> Spinner </div>
    }

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