[gatsby] Loading spinner

Suyeon·2020년 10월 25일
0

React

목록 보기
6/26

gatsby에서 페이지에 접속 후 initial loading이 되는동안 loding spinner를 보여주고 싶을 때 아래 방법을 사용하면 된다.

1️⃣ It will copy the default-html.js file and rename it as html.js and will place it in our src directory.
cp .cache/default-html.js src/html.js

2️⃣ Add a spinner to html.js

// html.js
import React from "react"
import PropTypes from "prop-types"
import LoaderSVG from './img/loader.svg'

export default function HTML(props) {
  return (
    <html {...props.htmlAttributes}>
      <head>
        <meta charSet="utf-8" />
        <meta httpEquiv="x-ua-compatible" content="ie=edge" />
        <meta
          name="viewport"
          content="width=device-width, initial-scale=1, shrink-to-fit=no"
        />
        {props.headComponents}
      </head>
      <body {...props.bodyAttributes}>
        {props.preBodyComponents}
        <div
              key={`loader`}
              id="___loader"
              style={{
                alignItems: "center",
                backgroundColor: "#F2F2F2",
                display: "flex",
                justifyContent: "center",
                position: "absolute",
                left: 0,
                top: 0,
                right: 0,
                bottom: 0,
                zIndex: 100,
              }}
           >
           <img 
              src={LoaderSVG} 
              alt="loading spinner" 
              style={{ width: '40px', height: '40px'}} />
        </div>
        <div
          key={`body`}
          id="___gatsby"
          dangerouslySetInnerHTML={{ __html: props.body }}
        />
        {props.postBodyComponents}
      </body>
    </html>
  )
}

HTML.propTypes = {
  htmlAttributes: PropTypes.object,
  headComponents: PropTypes.array,
  bodyAttributes: PropTypes.object,
  preBodyComponents: PropTypes.array,
  body: PropTypes.string,
  postBodyComponents: PropTypes.array,
}

3️⃣ Add it to gatsby-browser.js

// gatsby-browser.js
export const onInitialClientRender = () => {
    setTimeout(function() {
        document.getElementById("___loader").style.display = "none"
    }, 1000)
}
profile
Hello World.

0개의 댓글