Home > other >  Nextjs react-bootstrap onSubmit doesn't work
Nextjs react-bootstrap onSubmit doesn't work

Time:05-03

Details

I want to make a form for a register page, after entering the form and hitting submit, the react-bootstrap button will call handleSubmit() using onSubmit={}.

Expected and actual result

I tried multiple ways to write onSubmit={}, you can see some of them in the Form tag. None of them worked. But the third one, console.log(), did get executed twice when submit button is clicked.

What I have tried

I don't where to start debugging this, so I tried way to write onSubmit and the function

  • Anonymous function in onSubmit={}

  • Anonymous async function in onSubmit={}

  • Anonymous function

  • Anonymous async function

  • top-level function

  • top-level async function

  • onSubmit={e=>console.log(e)}

None of these worked during testing.

Code

here is a simplified sample with the same problem.

import { Form, Button } from "react-bootstrap";

export default function Home() {

    const handleSubmit = (event) => {
        event.preventDefault()
        console.log("test");
    };

    return (
        <>
            <Form
                noValidate
                // onSubmit={e=>handleSubmit(e)}
                onSubmit={handleSubmit}
                // onSubmit={console.log("hello world")}
            >
                <Form.Group>
                    <Form.Label>Username</Form.Label>
                    <Form.Control
                        onChange={() => handleCheck}
                        type="text"
                        defaultValue={"test"}
                        required
                    />
                </Form.Group>
                <Button type="submit">
                    Submit
                </Button>
            </Form>
        </>
    );
}

CodePudding user response:

handleSubmit should get a preventDefault():

const handleSubmit = (e) => {
  e.preventDefault()
  console.log("test")
}

You're also bringing in useState but no where are you showing how you're using it. You could always update state from handleSubmit.

CodePudding user response:

I think I have found the problem.

The reason I use console.log() to check whether the function is executed is because I want to print out some value. I expected it to print out in the terminal, but this is the front end, all console.log() goes to browser console, instead of terminal. So the code onSubmit={handleSubmit} did execute properly.

Play around with the official example : Nextjs Doc: Building forms

  • Related