0
votes

I'm trying to set up a function inside a React-Redux component that uses Redux Form that will call the form's onSubmit method, but I'm not sure of the correct way to write it so that onSubmit gets called correctly.

So far I think the correct approach is to create refs, and then use those refs in the function to refer to the form. In the example below in the form tag, handleSubmit and submit are already defined in render.

// example function that should submit form
submitForm = e => {
    const { submit } = this.formRef;
    const { handleSubmit, onSubmit } = this.formRef;
    this.formRef.onSubmit()
  };

// form opening tag
<form className="my-form" ref={this.formRef} onSubmit={handleSubmit(submit)}>

I expect this function to submit the form, but in this case this throws an error that says "TypeError: _this.formRef.onSubmit is not a function." I get the same error if I use this.formRef.handleSubmit(), this.formRef.handleSubmit(submit), or this.formref.onSubmit(submit). In the submitForm function, this.formRef returns a value so I know the ref is working correctly.

1
form has a .submit() function I think - Hameda169
@Hameda169 I tried writing this.formRef.submit(), but no luck there. - kmid5280

1 Answers

0
votes

Your approach is wrong. You need to do this:

const [inputData, setInputData] = useState('');

changeHandler = e => {
    setInputData(e.target.value)
}

handleSubmit= e => {
    API.sendForm(inputData)
  };

// form opening tag
<form className="my-form">
<input onChange={changeHandler} value={inputData}/>
<button onClick={handleSubmit} value="Submit Form"/>
</form>

Perhaps your example will work if you fix the error:

// add () => 
<form className="my-form" ref={this.formRef} onSubmit={() => handleSubmit(submit)}>