I start learning react about 2 month ago. Right now I am trying to build my portfolio with some interactive design using spline 3d. The problem is the loading time is too long and I want to make a loading screen that stop loading exact time when my 3d start element render
I did the below and I'm pretty happy with it. This is for react router v6 with loader functions.
Note that the loading screen will be displayed only while the loader function is being executed. If you want to keep showing it after a route component is rendered and dismiss it from within the component you could pass the setLoaded
function as a prop to your component in the router configuration.
import React, { useState, useEffect } from 'react';
import {
createBrowserRouter,
Outlet,
RouterProvider,
} from 'react-router-dom';
// Have a function for creating your router so that you can pass
// a function as a prop to your page wrapper, in order for it to let
// you know when a page has loaded
const wireRouter = (setLoaded) => createBrowserRouter([
{
path: '/',
element: <PageWrapper setLoaded={setLoaded} />,
children: [
{
path: '/*',
element: <PageNotFound />,
},
{
path: '/',
element: <Home />,
},
{
path: '/pageThatLoadsSomething/',
element: <PageThatLoadsSomething />,
loader: () => functionThatLoadsSomething(),
}
]
}
]);
// In your page wrapper set loaded to true immediately after you render
function PageWrapper({ setLoaded }) {
useEffect(() => {
setLoaded(true);
}, []);
return <Outlet />;
}
// Make a root component that keeps state of whether a page is loaded
// and pass the setter to update it to the function that creates your
// router. Render a loader component conditionally, while the page is
// not loaded.
function Root() {
const [pageLoaded, setLoaded] = useState(false);
return (
<React.StrictMode>
{ !pageLoaded ? <Loading /> : null }
<RouterProvider router={wireRouter(setLoaded)} />
</React.StrictMode>
);
}
ReactDOM.createRoot(document.getElementById('root')).render(<Root />);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With