1

I have a component that looks like this:

const App = (): ReactElement => {
    
    const submitFeedbackHandler = (e: FormEvent): void => {
        e.preventDefault();
        // ...
    }

    return <>
        <form onSubmit={submitFeedbackHandler}>
            // ...
            <button type='submit'>Submit</button>
        </form>
    </>

}

Problem is, no matter how I try to call submitFeedbackHandler from onSubmit it doesn't work. I tried onSubmit={(e) => submitFeedbackHandler(e)}, but no luck either. How can I get this to work so that I can do e.preventDefault()?

4
  • 1
    Does the page reload upon submit? Do you get any typecheck error? Are FormEvent & ReactElement imported? Commented Dec 12, 2020 at 23:45
  • Yes, the page reloads en no errors, and yes FormEvent and ReactElement are imported. The function submitFeedbackHandler is just not called at all when the form submits. Commented Dec 12, 2020 at 23:52
  • 1
    That's odd. It should work as expected. Can you show the whole component you're working? Maybe there's something in your code that you didn't show preventing the event to dispatch. Commented Dec 13, 2020 at 0:15
  • I found the problem. I had added required to some inputs in the form. Oddly enough, this stops onSubmit completely from being called. Even simply calling () => console.log('onSubmit!') didn't work, so I removed all the required tags from the inputs within the forms and it works fine now. I'll do validation of empty fields myself in that case instead of relying on the required tag on inputs. Commented Dec 13, 2020 at 0:19

1 Answer 1

1

This might give some headache to inexperienced React developers like myself, so here's the answer to the problem:

I had added the required tag to some inputs in the form. Oddly enough, this stops onSubmit completely from being called. Even simply calling onSubmit = {() => console.log('onSubmit!')} didn't work, so I removed all the required tags from the inputs within the form and it works fine now. I'll do validation of empty fields myself in that case instead of relying on the required tag on inputs.

I think it has to do with controlled and uncontrolled components in React. Will do further research to see exactly what causes this. Thank you @Julius Guevarra for your help.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.