reactjsformsreact-hooksonsubmituse-ref

React - Trigger form submit using useRef


Good day, so I am trying to perform an intermediate function before a form action="POST" takes place. Ive tried two things firstly onSubmit={functionName} but the form always performs the action even if in the onSubmit function I return false. Secondly ive been trying to useRef instead to dispatch the submit event programtically but nothing happens? I essentially have to do a server side call to get a config for the form values that gets posted, unfortunately the external API I use needs the form to be submitted in this way. Please any help would be greatly appreciated.

Attempt 1:

const performSubmit =() => {
 //Using onSubmit and then only performing the return after the axios call is done
 axiosCallFunction.then((res) => {
   setConfig(res.data)
   return true
 }).catch((error)) => {
   //Dont submit form
   return false
 })
}

return (
<form name="form" onSubmit={performSubmit} id="x1" method="POST" action="https://url.aspx" target="_top">
    <input value={config.param}/>
    <button type="submit"> Submit</button>
</form>)

Attempt 2

const formEl = useRef();

const performSubmit =() => {
 //Currently not calling the submit on the form
 formEl.current.dispatchEvent(new Event("submit"))
}

return (
<form name="form" ref={formEl} id="x1" method="POST" action="https://url.aspx" target="_top">
    <input value={config.param}/>
    <button onClick={performSubmit} />
</form>)

Essentially want to do some call to a server and get results back before I submit the form or perform the action for the form.


Solution

  • Have you tried:

    formEl.current && formEl.current.submit();
    

    ?