Some User
Some User

Reputation: 5827

React - Preventing Form Submission

I've been experimenting with React. In my experiement, I'm using the Reactstrap framework.When I click a button, I've noticed that the HTML form submits. Is there a way to prevent form submission when a button is clicked?

I've recreated my issue here. My form is pretty basic and looks like this:

<Form>
  <h3>Buttons</h3> 
  <p>
    <Button color="primary" onClick={this.onTestClick}>primary</Button>&nbsp;
  </p>
</Form>

What am I missing?

Upvotes: 120

Views: 265889

Answers (15)

Mayank Kumar Chaudhari
Mayank Kumar Chaudhari

Reputation: 18538

In my case, I had done a typing error - used onClick in place of onSubmit.

Make sure you use onSubmit event handler and not onClick on the form element.

Upvotes: 0

HaukurHaf
HaukurHaf

Reputation: 13796

No JS needed really ... Just add a type attribute to the button with a value of button

<Button type="button" color="primary" onClick={this.onTestClick}>primary</Button>&nbsp;

By default, button elements are of the type "submit" which causes them to submit their enclosing form element (if any). Changing the type to "button" prevents that.

EDIT: Be careful with this simple solution though, because it will prevent users from submitting the form using the ENTER key as people have mentioned in the comments below.

Upvotes: 103

Aakash
Aakash

Reputation: 23717

I was facing this problem when I used preventDefault() with destructuring. It worked perfectly fine without destructuring:

// this works
const handleClick = (evt) => {
   evt.preventDefault();
}

// this doesn't work
const handleClick = ({preventDefault}) => {
   preventDefault();
}

Upvotes: 1

Pruteanu Alexandru
Pruteanu Alexandru

Reputation: 247

<button type="submit" onClick={(e)=> this.submitInfo(e)}>Prevent Submit</button>

And the function

submitInfo = (event)=>{
    event.preventDefault();
      .....

}

Upvotes: -1

1252_SHIVAM KUMAR
1252_SHIVAM KUMAR

Reputation: 11

import React from 'react'
import Button from './button'
import Input from './input'

function Form(){

    function handleSubmit(event){
        event.preventDefault();
    }

    return(
        <div>
            <h1>FORM</h1>
            <form onSubmit={handleSubmit}>
                <Input type = 'text' placeholder = "What's Your Name?" />
                <Button buttonText = 'Submit' />
            </form>
        </div>
    );
}

export default Form;

Upvotes: 1

Sakil Khan
Sakil Khan

Reputation: 140

import React, { Component } from 'react';

export class Form extends Component {
  constructor(props) {
    super();
    this.state = {
      username: '',
    };
  }
  handleUsername = (event) => {
    this.setState({
      username: event.target.value,
    });
  };

  submited = (event) => {
    alert(`Username: ${this.state.username},`);
    event.preventDefault();
  };
  render() {
    return (
      <div>
        <form onSubmit={this.submited}>
          <label>Username:</label>
          <input
            type="text"
            value={this.state.username}
            onChange={this.handleUsername}
          />
          <button>Submit</button>
        </form>
      </div>
    );
  }
}

export default Form;

Upvotes: 4

Yonatan Dawit
Yonatan Dawit

Reputation: 647

Make sure you put the onSubmit attribute on the form not the button in case you have a from.

<form onSubmit={e => e.preventDefault()}>
    <button onClick={this.handleClick}>Click Me</button>
</form>

Make sure to change the button onClick attribute to your custom function.

Upvotes: 20

dougoftheabaci
dougoftheabaci

Reputation: 704

There's another, more accessible solution: Don't put the action on your buttons. There's a lot of functionality built into forms already. Instead of handling button presses, handle form submissions and resets. Simply add onSubmit={handleSubmit} and onReset={handleReset} to your form elements.

To stop the actual submission just include event in your function and an event.preventDefault(); to stop the default submission behavior. Now your form behaves correctly from an accessibility standpoint and you're handling any form of submission the user might take.

Upvotes: 3

prajakta gadhave
prajakta gadhave

Reputation: 1

componentDidUpdate(){               
    $(".wpcf7-submit").click( function(event) {
        event.preventDefault();
    })
}

You can use componentDidUpdate and event.preventDefault() to disable form submission.As react does not support return false.

Upvotes: -8

Pawel
Pawel

Reputation: 18212

preventDefault is what you're looking for. To just block the button from submitting

<Button onClick={this.onClickButton} ...

code

onClickButton (event) {
  event.preventDefault();
}

If you have a form which you want to handle in a custom way you can capture a higher level event onSubmit which will also stop that button from submitting.

<form onSubmit={this.onSubmit}>

and above in code

onSubmit (event) {
  event.preventDefault();

  // custom form handling here
}

Upvotes: 44

Gokhan Kurt
Gokhan Kurt

Reputation: 8277

You have prevent the default action of the event and return false from the function.

function onTestClick(e) {
    e.preventDefault();
    return false;
}

Upvotes: 3

eddywashere
eddywashere

Reputation: 2618

I think it's first worth noting that without javascript (plain html), the form element submits when clicking either the <input type="submit" value="submit form"> or <button>submits form too</button>. In javascript you can prevent that by using an event handler and calling e.preventDefault() on button click, or form submit. e is the event object passed into the event handler. With react, the two relevant event handlers are available via the form as onSubmit, and the other on the button via onClick.

Example: http://jsbin.com/vowuley/edit?html,js,console,output

Upvotes: 136

EQuimper
EQuimper

Reputation: 5929

2 ways

First one we pass the event in the argument right into the onClick.

  onTestClick(e) {
    e.preventDefault();
    alert('here');
  }

  // Look here we pass the args in the onClick
  <Button color="primary" onClick={e => this.onTestClick(e)}>primary</Button>&nbsp;

Second one we pass it into argument and we did right in the onClick

  onTestClick() {
    alert('here');
  }

  // Here we did right inside the onClick, but this is the best way
  <Button color="primary" onClick={e => (e.preventDefault(), this.onTestClick())}>primary</Button>&nbsp;

Hope that can help

Upvotes: 8

fvgs
fvgs

Reputation: 21982

function onTestClick(evt) {
  evt.stopPropagation();
}

Upvotes: 2

Soviut
Soviut

Reputation: 91525

In your onTestClick function, pass in the event argument and call preventDefault() on it.

function onTestClick(e) {
    e.preventDefault();
}

Upvotes: 4

Related Questions