3

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?

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

import SpinnerLoader from "../components/SpinnerLoader.jsx";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.