Reputation: 465
I have an issue with reloading a blank page after submitting a contact form. Contact form is working, email is sending to me but after that itself loading a blank page.
I would prefer it to act like this: submiting a form -> sending an message -> clearing values -> without reloading.
So I know about e.preventDefault()
I tried to use it but for it I need an additional funcion to pass e
prop. For example:
But I can't pass a hook into the function.
const handleSubmit (e: any) => {
const [state, handleSubmit] = useForm('xwkjewea');
e.preventDefault()
if (state.succeeded) {
formRef.current.resetFields();
formRef.current.message.success('Wiadomość została wysłana');
}
}
I'm using FormSpree to service my message sending and for properly working it I needed to do it like below:
const Contact = () => {
const formRef = useRef<any>();
const captchaRef = useRef<HCaptcha>(null);
const [token, setToken] = useState<string>('');
const [state, handleSubmit] = useForm('formSpree-id');
if (state.succeeded) {
formRef.current.resetFields();
formRef.current.message.success('Sent');
}
const onExpire = () => {
setToken('');
message.warning('Expired');
};
const onError = (err: string) => {
setToken('');
message.error(`${err}`);
};
return (
<Wrapper>
<Title>Contact</Title>
<MessageForm
ref={formRef}
name='nest-messages'
onFinish={handleSubmit}
validateMessages={validateMessages}
>
[...]
Upvotes: 1
Views: 166
Reputation: 4632
You can use the e.preventDefault()
in a anonymous function and then pass the e
event through to the handleSubmit
function.
<MessageForm
ref={formRef}
name="nest-messages"
onFinish={(e) => {
e.preventDefault();
handleSubmit(e);
}}
validateMessages={validateMessages}
>
I do recommend put the state.succeeded
check in a useEffect
to avoid clearing the form when other states change
useEffect(() => {
if (state.succeeded) {
formRef.current.resetFields();
formRef.current.message.success("Sent");
}
}, [state.succeeded]);
Upvotes: 1