React - Display loading screen while DOM is rendering?

前端 未结 19 1729
我在风中等你
我在风中等你 2020-11-28 00:29

This is an example from Google Adsense application page. The loading screen displayed before the main page showed after.

I don\'t know how to do the same th

19条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 00:51

    I'm also using React in my app. For requests I'm using axios interceptors, so great way to make loader screen (fullpage as you showed an example) is to add class or id to for example body inside interceptors (here code from official documentation with some custom code):

    // Add a request interceptor
    axios.interceptors.request.use(function (config) {
        // Do something before request is sent
         document.body.classList.add('custom-loader');
         return config;
      }, function (error) {
        // Do something with request error
        return Promise.reject(error);
      });
    
    // Add a response interceptor
    axios.interceptors.response.use(function (response) {
        // Do something with response data
           document.body.classList.remove('custom-loader');
           return response;
      }, function (error) {
        // Do something with response error
        return Promise.reject(error);
      }); 
    

    And then just implement in CSS your loader with pseudo-elements (or add class or id to different element, not body as you like) - you can set color of background to opaque or transparent, etc... Example:

    custom-loader:before {
        background: #000000;
        content: "";
        position: fixed;
        ...
    }
    
    custom-loader:after {
        background: #000000;
        content: "Loading content...";
        position: fixed;
        color: white;
        ...
    }
    

提交回复
热议问题