简体   繁体   中英

How to prevent loading blank page after submitting form?

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}
      >
    [...]

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]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM