I'm encountering an issue with a custom LoadingButton component in my React TypeScript project using the Material-UI (MUI) library. The problem arises when I use this LoadingButton within a form that has an onSubmit event handler. The LoadingButton has a type="submit", and when I click on it, the form's onSubmit event function does not get executed. However, if I remove the setLoading(true) call from the handleClick function of the LoadingButton, the form submission works as expected.
Below is the code for the LoadingButton component:
import { Button, ButtonProps, CircularProgress } from "@mui/material";
import React, {
forwardRef,
MouseEvent,
useImperativeHandle,
useState,
} from "react";
interface LoadingButtonWrapperProps extends ButtonProps {
// You can add other custom props here if needed
}
interface LoadingButtonWrapperHandle {
disableLoading: () => void;
}
const LoadingButton = forwardRef<
LoadingButtonWrapperHandle,
LoadingButtonWrapperProps
>((props, ref) => {
const [loading, setLoading] = useState<boolean>(false);
// Expose the setLoading function to the parent component
useImperativeHandle(ref, () => ({
disableLoading,
}));
const disableLoading = () => {
setLoading(false);
};
const handleClick = (e: MouseEvent<HTMLButtonElement>) => {
if (props.onClick) {
props.onClick(e);
}
setLoading(true);
};
return (
<>
{loading ? <CircularProgress size={24} /> : null}
<Button {...props} disabled={loading} onClick={handleClick}>
{props.children}
</Button>
</>
);
});
export default LoadingButton;
Issue:-
When the setLoading(true) is called within the handleClick function, the form's onSubmit event does not get triggered. If I remove the setLoading(true) call, the form submission works correctly.
Steps to Reproduce -
- Create a form with an onSubmit event handler.
- Use the LoadingButton component with type="submit" inside the form.
- Click the LoadingButton to submit the form.
Expected Behavior The form's onSubmit event handler should be executed when the LoadingButton is clicked, even with the setLoading(true) call.
Actual Behavior The form's onSubmit event handler is not executed when the LoadingButton is clicked if setLoading(true) is called within the handleClick function of LoadingButton.
Thanks,