Skip to content

Instantly share code, notes, and snippets.

@iShubhamPrakash
Last active December 29, 2021 07:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iShubhamPrakash/47048bd91a72495f877401a02d51607c to your computer and use it in GitHub Desktop.
Save iShubhamPrakash/47048bd91a72495f877401a02d51607c to your computer and use it in GitHub Desktop.
A custom React+tailwind loading indicator
/**
* 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,
};
@iShubhamPrakash
Copy link
Author

This is how it looks-

<LoadingIndicator show={true} progress={60} />

Screenshot 2021-12-29 at 10 39 46 AM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment