0

I want add a preloader in my react application. The reason is, my application needs much time to load. So, I want that When all my application contents is fully ready to be load, it will be rendered automatically. A preloader will be rendering as long as my application takes time to get ready to be loaded. Is it possible to do?

I need help.

This is me App code given below:-

import React from 'react';
import Navbar from './Navbar'
import Home from './Home';
import About from './About';
import Services from './Services';
import Skills from './Skills';
import Contact from './Contact';
import Footer from './Footer';
import Reset from './Reset';

function App() {

  return (
    <>
      <Reset />
      <Navbar />
      <Home />
      <About />
      <Services />
      <Skills />
      <Contact />
      <Footer />
    </>
  );

}

export default App;

This is my Index.js code given below:-

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import Preloader from './Preloader'

ReactDOM.render(
  <App/>
  ,document.getElementById('root')
);
Zidan Mehedi
  • 3
  • 1
  • 3

3 Answers3

0

Depending on what you want to achieve you have many options on doing this. That is the goal of using frameworks like React. My advice is, separate the loading of data( API calls etc.) from the loading of UI. Use async methods for loading the data where you can do that. I see that you are using functional components, so look into react hooks and generating the data using states. You have a way of setting a default value to a state so everything could render independently from the data generation. Later when the state is set to your data the site will render automatically with the new data.

Specifically to setting a preload ui you can check this post: React - Display loading screen while DOM is rendering?

0

We usually make an API call and until the data is ready we show a loader. An SVG Loader or any other loader.

You basically need to set three states to maintain loading, error and your data: Use the following setup this will be helpful in your project. Also visit my github project to get Loader Code from API and Loader

function App() {
  const [tours, setTours] = useState([]);
  const [error, setError] = useState(false);
  const [loading, setLoading] = useState(false);

  /*--- I am using fetch API here
  useEffect(() => {
    setLoading(true);
    fetch(url)
      .then((response) => {
        if (response.status >= 200 && response.status < 300) {
          return response.json();
        } else {
          throw new Error("Could not fetch data");
        }
      })
      .then((tours) => {
        setLoading(false);
        setTours(tours);
      })
      .catch((err) => console.log(err));
  }, []);
  ---*/

  const fetchTours = async () => {
    try {
      const response = await fetch(url);
      const tours = await response.json();
      setLoading(false);
      setTours(tours);
    } catch (error) {
      setLoading(false);
      setError(true);
    }
  };
  useState(() => {
    setLoading(true);
    fetchTours();
  }, []);
  // Functionality 1: Not Interested Button click
  const handleBtnClick = (id) => {
    const updatedTours = tours.filter((tour) => tour.id !== id);
    setTours(updatedTours);
  };

  // Functionality 2: Refresh Button click

  const handleRefresh = () => {
    setLoading(true);
    fetchTours();
  };

  // Let us do conditional rendering
  if (loading) {
    return (
      <div style={{ textAlign: "center", margin: "2rem 0" }}>
        <Loader />
      </div>
    );
  }

  if (error) {
    return <p>Error ...</p>;
  }

  return (
    <section>
      <p className="our-tours">
        {tours.length > 0 ? (
          "Our Tours"
        ) : (
          <div>
            <p>No Tours Left</p>
            <button className="btn" onClick={handleRefresh}>
              Refresh
            </button>
          </div>
        )}{" "}
      </p>
      <main className="App">
        {tours.length > 0 && (
          <Tours tours={tours} handleClick={handleBtnClick} />
        )}
      </main>
    </section>
  );
}

export default App;

There are three scenarios:

  1. Initially our loading is true and we show our loader.

  2. When the data has successfully arrived, we start showing the data and hide our Loader.

  3. When there is an error in our API call, we show the error message.

The above setup works in all cases :)

Imran Rafiq Rather
  • 7,677
  • 1
  • 16
  • 35
0

If you're using reactjs, you need to make a component so try this:

import { useEffect } from "react";
import { Rings } from "react-loader-spinner";
const Loader = () => {
  useEffect(() => {
    window.onload=()=>{
        const preloader = document.querySelector(".preloader");
        preloader.remove();
      }
  });
  return <LoaderFile/>
// which have your preloader html and having class is `.preloader`
};

export default Loader;

In App.js File


 const App = () => {
  return (
    <>
    <Loader /> // Add Loader Component here
      <Router>
        <Routes>
          <Route path="/" element={<Navigation />}>
            <Route index element={<Main />} />
          </Route>
        </Routes>
      </Router>
    </>
  );
};
Kannu Mandora
  • 479
  • 2
  • 10
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 09 '23 at 18:04