Reactjs: formsubmit.co doesn't redirect to it's page

81 Views Asked by At
const InputPhone = (props) => {
    const {control} = useForm();
    const [telValue, setTelValue] = useState('');

    const handleSubmit = async () => {
        const emailData = {
            attachment: 'Order recieved',
            html: telValue
        };

        try {
            const response = await axios.post('https://formsubmit.co/el/cimewa', emailData);
            console.log('Email sent:', response.data);
        } catch (error) {
            console.error('Email error:', error);
        }
    };
<Btn click={handleSubmit}>Order</Btn>
const Input = () => {
    const {control, formState: {errors}, handleSubmit} = useForm()
    const onSubmit = (data) => {
        alert(JSON.stringify(data))
    }

    return (
        <div>
            <form onSubmit={handleSubmit(onSubmit)} className={cl.form} method='post'>

Nothing happens when I press the button. But if I use test form on formsubmit.co website - it redirects me. How to fix that? Couldn't fix it even with Chatgpt. It's saying to me that all is ok, or generates the same code I use. Thanks!

1

There are 1 best solutions below

3
Anh Tran On

In formsubmit.co, the form is submitted through a POST action <form method="post" url="destination_url"> which will redirect to the destination_url. This is the default on submit behavior of the HTML form element. In react, when you use react-hook-form, the handleSubmit function is now the on submit event handler which is a custom handler implemented by the library. The reason why it is not redirecting you is that it is implemented this way

const handleSubmit = (submitCallback) => (e) => {
  e.preventDefault(); // prevent redirecting to destination_url
  // other extra code
}

Now if you want to redirect your user to any endpoint just modify the trycatch block in the submit callback

try {
  const response = await axios.post('https://formsubmit.co/el/cimewa', emailData);
  console.log('Email sent:', response.data);
  window.location = 'destination_url' // redirect with window.location if this destination_url is an external URL
  // or use navigate of react-router-dom if it is an internal URL of your app 
} catch (error) {
  console.error('Email error:', error);
}

Hope this could help!