I’m trying to make a page loader so I’ve made a Loader
component that must add load event on window
but it doesn’t work at all:
import React, {useEffect} from "react"
import './loader.sass'
const Loader = () => {
useEffect(() => {
console.log("Loading")
window.addEventListener('load', () => console.log('Loaded'))
}, [])
return (
<div id="loader">
<div className="center">
<div className="rect"></div>
<div className="rect"></div>
</div>
</div>
)
}
export default Loader
In App.jsx
file this component is imported first so, as I think, it must render first and launch event listener, but nothing happens.
Is there something I don’t understand in React render? Please tell me if you know any other way to make a page loader. I’ve already tried putting addEventListener
in index.html
file and in that case load
event fires too early.
I’ve just tried Suspense and lazy, but this approach doesn’t wait for styling and images.
2
Answers
For creating a loader component just use this code that shows loader for 2 sec.
The process can be broken down into three main steps:
Step 1, Creating the Loader Component:
Step 2: Designing a
Higher-Order Component (HOC)
and Combining with the LoaderStep 3: Wrapping the Target Component with the
HOC