I've created a web app with react js. I did every thing well and site is running pretty fine. Though it run well, i need to modify some things. Like when i visit my nav links, it takes few time to load the component. So i want to show a spinner while the component in loading. How can i do this? Is there any way to do this?
CodePudding user response:
Using Mui circularprogress
and making a state called isFetching (which will be turned off after all content is fetched)
For mui (see: https://mui.com/material-ui/react-progress/#circular-indeterminate)
import React, { useState, useEffect } from "react";
import CircularProgress from "@mui/material/CircularProgress";
import Box from "@mui/material/Box";
export default function App() {
const [isFetching, setIsFetching] = useState(true);
useEffect(() => {
setTimeout(function () {
console.log("Delayed for 5 second.");
setIsFetching(false);
}, 5000);
}, []);
if (isFetching) {
return (
<Box sx={{ display: "flex", justifyContent: "center" }}>
<CircularProgress />
</Box>
);
}
return <div>content....</div>;
Example:
https://codesandbox.io/s/vigilant-water-e6l0bk?file=/src/App.js:0-571
I used setTimeout to substitute an API fetch call. After 5 seconds the content would load otherwise a spinner is shown on the screen.
CodePudding user response:
You can maintain the state in your component. Initially, it can be set as true. Whenever you're doing an API call, based on the response you can change the state according to your needs. And based on this state you can render a spinner or the content.