Skip to content

Instantly share code, notes, and snippets.

@lyjacky11
Last active November 17, 2022 23:28
Show Gist options
  • Save lyjacky11/4225b7099ec72e0f69566febe56cd3cb to your computer and use it in GitHub Desktop.
Save lyjacky11/4225b7099ec72e0f69566febe56cd3cb to your computer and use it in GitHub Desktop.
React Loading Spinner using Bootstrap
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