I am trying to add a loader icon to my site but it is constantly showing should i put it in a component and import it? The state is set to true as the page is loading when it refreshes maybe its something with this.

This is my app.js file

import React from "react";

import { createBrowserHistory } from "history";
import { Router, Route, Switch } from "react-router-dom";

import "assets/scss/material-kit-react.scss?v=1.4.0";

// pages for this product
import LandingPage from "views/LandingPage/LandingPage.jsx";
import ProfilePage from "views/ProfilePage/ProfilePage.jsx";
import { css } from "@emotion/core";
// First way to import
import { ClipLoader } from "react-spinners";

const override = css`
  display: block;
  margin: 0 auto;
  border-color: red;
`;
var hist = createBrowserHistory();

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true
    };
  }
  render() {
    return (
      <>
        <ClipLoader
          css={override}
          sizeUnit={"px"}
          size={150}
          color={"#123abc"}
          loading={this.state.loading}
        />
        <Router history={hist}>
          <Switch>
            <Route path="/profile-page" component={ProfilePage} />
            <Route path="/" component={LandingPage} />
          </Switch>
        </Router>
      </>
    );
  }
}

1 Answers

0
TRomesh On

your default state is set to true. so it will show the loading once the component renders

   this.state = {
      loading: false
    };

You can change your Loader to a HOC

import React from 'react';
import { ClipLoader } from "react-spinners";

function Loading(Component) {
  return function WihLoadingComponent({ isLoading, ...props }) {
    if (!isLoading) return (<Component {...props} />);
    return (<ClipLoader
          css={override}
          sizeUnit={"px"}
          size={150}
          color={"#123abc"}
          loading={isLoading}
        />);
  }
}
export default Loading;

Then you can use you global context or redux store to update the state of isLoading

render() {
    return (
      <Loading isLoading={this.props.isLoading} data={data} />
    )
  }