Last active
December 29, 2021 07:07
-
-
Save iShubhamPrakash/47048bd91a72495f877401a02d51607c to your computer and use it in GitHub Desktop.
A custom React+tailwind loading indicator
This file contains hidden or 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
/** | |
* Author: https://shubhamprakash.dev | |
* Description: This is a custom LoadingIndicator component that can be used in any React project with Tailwind css. | |
**/ | |
import React, { useEffect, useRef, useState } from "react"; | |
import PropTypes from "prop-types"; | |
export const LoadingIndicator = ({ show, color, progress, height }) => { | |
const [width, setWidth] = useState(0); | |
const intervalId = useRef(null); | |
const showLoading = Array.isArray(show) | |
? show.some((item) => Boolean(item)) | |
: show; | |
useEffect(() => { | |
if (progress !== undefined) { | |
clearInterval(intervalId.current); | |
return setWidth(progress); | |
} | |
if (!intervalId.current) { | |
intervalId.current = setInterval(() => { | |
setWidth((width) => { | |
if (width >= 100) return 0; | |
return width + 1; | |
}); | |
}, 10); | |
} | |
return () => clearInterval(intervalId.current); | |
}, [progress]); | |
if (!showLoading) return null; | |
const loadingColor = color || "bg-blue-400"; | |
const loadingHeight = height || "h-2"; | |
return ( | |
<div className={`${loadingHeight} w-full bg-gray-200`}> | |
<div | |
className={`h-full ${loadingColor}`} | |
style={{ width: `${width}%` }} | |
/> | |
</div> | |
); | |
}; | |
LoadingIndicator.protoTypes = { | |
/** show: This can either be a boolean or an array of boolean. In case an array is passed, | |
* the loading indicator will be shown if any of the array item will be true **/ | |
show: PropTypes.oneOfType([PropTypes.bool, PropTypes.array]).isRequired, | |
/** color: A tailwind bg color className. This will be the color of the loading indicator **/ | |
color: PropTypes.string, | |
/** progress: This is the progress of the loading indicator. This is a number between 0 and 100 **/ | |
progress: PropTypes.number, | |
/** height: A tailwind height className. This is the height of the loading indicator **/ | |
height: PropTypes.string, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is how it looks-