I would like to create a custom button component that shows a loading spinner within itself when it's pressed and with a condition that can be externally defined which will tell the button to remove the spinner and return to its original appearance. Something like this:
<CustomButton
type="button"
className="btn btn-primary"
stopSpinningWhen={condition}
onClick={() => ...}
>
Click me
</CustomButton>
Currently, my buttons with a spinner look like this, which is super fine, but it's a pain to write repetitive code/states for each single button:
const [buttonSpinner, setButtonSpinner] = useState(false);
const onClickEvent = (ev) => {
setButtonSpinner(true);
if (condition) {
setButtonSpinner(false);
}
};
return (
<button
type="button"
className="btn btn-primary"
onClick={onClickEvent}
disabled={buttonSpinner}
>
{buttonSpinner ? (
<span
className="spinner-border spinner-border-sm"
role="status"
aria-hidden="true"
></span>
) : (
"Click me"
)}
</button>
);
I'm using React 17.0.2.
Is it even possible?