DOM이 ReactJS에서 렌더링되는 동안 로딩 스피너를 표시하는 방법

개요



디자인은 어떤 제품을 만들 때 중요한 단계입니다. 사용자 경험은 사용자의 관심을 끌고 유지하는 데 중요합니다. 많은 사용자가 우리 애플리케이션의 실제 크기와 HTTP 요청 또는 빌드 시간과 같은 작업이 얼마나 오래 걸릴 수 있는지 이해하지 못합니다. 그들이 우리 웹사이트를 방문했지만 빈 화면이 소개되면 웹사이트가 깨질 수 있다고 생각하고 다른 웹사이트로 이동합니다.

이 자습서에서는 사용자가 사이트를 방문할 때 웹 사이트의 다른 구성 요소가 여전히 로드 중임을 나타내기 위해 단순히 큰 로드 스피너를 추가하여 웹 사이트의 사용자 경험을 연마하는 방법을 보여줍니다.

1. 프로젝트 설정



우리는 React 프로젝트를 설정해야 합니다. 이 튜토리얼에서는 create-react-app을 사용할 것입니다. 터미널/CMD에서 다음을 입력합니다.
npx create-react-app loading-spinner

2. index.html 편집



index.html을 여는 첫 번째 단계입니다. "loader"클래스가 있는 하위 div가 있는 "loader-container"클래스가 있는 div를 추가할 것입니다. 이것은 HTML 내에서 로딩 스피너의 진입점이 될 것입니다. ReactJS에서 프로젝트는 index.html 파일, 특히 루트 div 내에서 렌더링됩니다. index.html에 로딩 스피너 클래스를 직접 추가하면 React 앱을 시작할 때 클래스를 표시할 수 있습니다.

<!-- Loading Spinner Div -->
    <div class="loader-container">
      <div class="loader"></div>
   </div>


이제 HTML 내에 진입점을 설정했으므로 CSS를 작성하여 로딩 스피너를 디자인해 보겠습니다. 동일한 index.html의 헤더 태그 내에 일부 CSS를 추가해 보겠습니다.

<head>
    <!-- Loading Spinner Styling -->
    <style>
      .loader {
        border: 16px solid #f3f3f3;
        border-top: 16px solid #3498db;
        border-radius: 50%;
        width: 130px;
        height: 130px;
        animation: spin 2s linear infinite;
      }

      @keyframes spin {
        0%  { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
      }
      </style>

</head>


이 시점에서 우리의 전체 index.html이 있어야 하는 방법은 다음과 같습니다. index.html 파일에 다음을 복사하여 붙여넣으십시오.

<!-- .../public/index.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <!--
      manifest.json provides metadata used when your web app is installed on a
      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
    -->
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <!--
      Notice the use of %PUBLIC_URL% in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>React App</title>

    <!-- Loading Spinner Styling -->
    <style>
      .loader {
        border: 16px solid #f3f3f3;
        border-top: 16px solid #3498db;
        border-radius: 50%;
        width: 130px;
        height: 130px;
        animation: spin 2s linear infinite;
      }

      @keyframes spin {
        0%  { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
      }
      </style>

  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>

    <!-- Loading Spinner Div -->
    <div class="loader-container">
      <div class="loader"></div>
   </div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
  </body>
</html>


3. App.js 편집



이제 App.js로 관심을 돌려 보겠습니다. 우리는 4가지 일을 할 것입니다:

애플리케이션의 상태를 관리할 수 있도록 상태 변수를 정의합니다.
요청을 시뮬레이트하는 함수 정의
시뮬레이션된 요청을 실행하려면 useEffect() React Hook을 사용하세요.
또는 상태 변수를 기반으로 HTML을 렌더링합니다.
먼저 App.js 파일의 맨 위에 있는 useState 및 useEffect를 가져와야 합니다.

//../src/App.js
import React, {useState, useEffect} from 'react';


이제 App() 함수 내에서 상태 변수를 정의할 수 있습니다. App() 함수를 정의한 직후에 다음을 추가합니다.

//../src/App.js

function App() {
  const [isLoading, setLoading] = useState(true);


React Hooks useState()를 활용하여 애플리케이션의 수명 주기 동안 변수의 값(또는 상태)을 추적할 수 있습니다. 이 예제에서는 부울 유형 변수를 추적하기 위해 useState()를 사용하고 있습니다. 응용 프로그램 전체에서 부울을 "true"에서 "false"로 전환할 것입니다. 가짜 요청으로 이동하여 상태 변수를 정의한 바로 아래에 다음을 추가합니다.

function someRequest() { //Simulates a request; makes a "promise" that'll run for 2.5 seconds
    return new Promise(resolve => setTimeout(() => resolve(), 2500));
  } 


Promise()를 반환하는 함수 someRequest()를 정의했습니다. Promise()는 두 개의 인수를 받는 JavaScript 메서드입니다. 성공 콜백 및 실패 콜백. 우리는 Promise()를 사용하여 해결을 시뮬레이트합니다. 실패할 것을 알고 코드에서 실패 콜백을 실행하여 시간 제한을 2.5초(또는 2500밀리초)로 설정합니다.

이제 useEffect() React Hook을 호출하여 someRequest() 함수를 호출할 수 있습니다. 이 함수는 index.html 내에서 로더 스피너 div를 제거하고 상태 변수를 토글합니다. someRequest() 함수 뒤에 다음 코드를 복사하여 붙여넣습니다.

useEffect(() => {
    someRequest().then(() => {
      const loaderElement = document.querySelector(".loader-container");
      if (loaderElement) {
        loaderElement.remove();
        setLoading(!isLoading);
      }
    });
  });


마지막으로 애플리케이션이 렌더링 시 로딩 스피너를 표시하려면 render() 메서드 바로 앞에 except를 추가해야 합니다. render() 메서드 직전에 App.js에 다음을 추가합니다.

if (isLoading) {
    return null;
  }


이제 터미널/CMD에서 다음 명령을 사용하여 애플리케이션을 실행합니다.
$ npm start이제 애플리케이션으로 표시되고(someRequest() 함수를 사용하여 시뮬레이션한 것처럼 서버에 일종의 요청을 하는 것으로 추정됨) 애플리케이션이 렌더링을 완료하면 사라지는 로딩 스피너가 있습니다.

Check out the full article on LateefLab

좋은 웹페이지 즐겨찾기