1

I am using preventDefault() but even then the page reloads. The below code looks similar to ReactJS form submit preventdefault not working. I also tried stopProgation() and nativeEvent.stopImmediatePropogation() as mentioned in React onClick and preventDefault() link refresh/redirect? but they didn't help either. Anything I'm missing?

Thanks in advance.

class CreateMember extends React.Component { constructor(props) { super(props); } render() { var handleSubmit = (e) => { e.preventDefault(); console.log('Event: Form Submit'); }; return ( <div> <Form onSubmit={this.handleSubmit}> <Form.Row> <Form.Group as={Col} controlId="mid"> <Form.Label>Member ID</Form.Label> <Form.Control required type="id" /> </Form.Group> <Form.Group as={Col} controlId="joiningDate"> <Form.Label>Joining Date</Form.Label> <Form.Control required type="date" /> </Form.Group> </Form.Row> <Button variant="primary" type="submit"> Create </Button> </Form> </div> ); } } 
1
  • remove "this" on your onSubmit="" because the handleSubmit button is declared inside a render method. Commented Apr 11, 2020 at 17:35

1 Answer 1

4

You are not defining "this.handleSubmit" as a class method. Instead you are defining a variable. "this.handlesubmit" is undefined. Define it as a class method without any variable declaration outside of render().

You also dont want to have any event handlers like this defined inside of render, as they dont need to be redeclared on every single call to render().

class CreateMember extends React.Component { constructor(props) { super(props); } handleSubmit = (e) => { e.preventDefault(); console.log('Event: Form Submit'); }; render() { return ( <div> <Form onSubmit={this.handleSubmit}> <Form.Row> <Form.Group as={Col} controlId="mid"> <Form.Label>Member ID</Form.Label> <Form.Control required type="id" /> </Form.Group> <Form.Group as={Col} controlId="joiningDate"> <Form.Label>Joining Date</Form.Label> <Form.Control required type="date" /> </Form.Group> </Form.Row> <Button variant="primary" type="submit"> Create </Button> </Form> </div> ); } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.