Last active
November 17, 2022 23:28
-
-
Save lyjacky11/4225b7099ec72e0f69566febe56cd3cb to your computer and use it in GitHub Desktop.
React Loading Spinner using Bootstrap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useState } from "react"; | |
import Spinner from "react-bootstrap/Spinner"; | |
const delayMs = 350; | |
let setTimeoutInstance; | |
export default function LoadingSpinner({ isLoading, children }) { | |
const [isDelayed, setIsDelayed] = useState(false); | |
useEffect(() => { | |
if (isLoading) { | |
setIsDelayed(false); | |
if (setTimeoutInstance) { | |
clearTimeout(setTimeoutInstance); | |
} | |
setTimeoutInstance = setTimeout(() => { | |
setIsDelayed(true); | |
}, delayMs); | |
} | |
}, [isLoading]); | |
return isDelayed ? ( | |
children | |
) : ( | |
<div className="vh-100 d-flex align-items-center justify-content-center"> | |
<Spinner | |
animation="border" | |
variant="light" | |
role="status" | |
style={{ width: "6rem", height: "6rem" }} | |
> | |
<span className="visually-hidden">Loading...</span> | |
</Spinner> | |
</div> | |
); | |
} | |
// USAGE: | |
import LoadingSpinner from "../components/LoadingSpinner"; | |
const [isLoading, setIsLoading] = useState(true); | |
useEffect(() => { | |
setIsLoading(true); | |
// [run some code] | |
setIsLoading(false); | |
}, []); | |
return ( | |
<LoadingSpinner isLoading={isLoading}> | |
{/* [children elements] */} | |
</LoadingSpinner> | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment