Friedman
Friedman

Reputation: 77

Why isn't onSubmit working for my React-Bootstrap form?

I have a form where I want people to put their email and a message. I set the onSubmit parameter for the form element to be my own function, however, it looks like the form is still using the default onSubmit function since the page always refreshes whenever I click the submit button, and does not print out what I say to print in my onSubmit function.

Looking a bit closer at the event functions for the form, I can see that there is an onSubmit function which is what I want to do and a submit function which is refreshing the page. For some reason it never runs my function (I never see what I'm logging to the console)!

Here is my code:

Form stuff:

<Card style={{marginLeft:"20%", marginRight:"20%"}}>
    <Card.Body>
    <Card.Title>Leave a Comment</Card.Title>
        <Form onSubmit={this.email} id="comments">
            <Form.Group>
                <Form.Label>Email address</Form.Label>
                <Form.Control type="email" placeholder="[email protected]" />
            </Form.Group>
            <Form.Group>
                <Form.Label>Message</Form.Label>
                <Form.Control as="textarea" rows="3"/>
            </Form.Group>
            <Button variant="primary" type="submit">
                Submit
            </Button>
        </Form>
    </Card.Body>
</Card>

Email Function:

email = () => {
        console.log("hello there I am working");
}

I saw one workaround which said to surround the form in a div like this:

<div
     onKeyDown={e => e.stopPropagation()}
     onClick={e => e.stopPropagation()}
     onFocus={e => e.stopPropagation()}
     onMouseOver={e => e.stopPropagation()}
     onSubmit={e => e.stopPropagation()}
     ... can add other events if they are giving you issues
>

but that didn't work either. Any ideas on what is going wrong?

Upvotes: 4

Views: 6428

Answers (1)

Dinesh Nadimpalli
Dinesh Nadimpalli

Reputation: 1491

You should prevent the default form submit inside the function which gets called on submit using .preventDefault() method.

In your case it is the email function which is called onSubmit. Modifying your email function as shown below might solve your problem

email = (e) => {
    e.preventDefault();
    console.log("hello there I am working");
}

Upvotes: 3

Related Questions