user9675077
user9675077

Reputation: 3

React conditional rendered Form auto submits

While developing an personal side project i've came across a notice i've not encountered before.

In the highest component there is a ternary, each containing a simple form:

{ this.state.isConnected
      ? <Chat handleSubmit={ this.handleChatSubmit } />
      : <Register handleSubmit={ this.handleRegisterSubmit } />
}

When the state changes (isConnected) it shows the Chat. The chat contains an form, so that the user can use the button and keys to submit their message. However, when i use the form element, it gives the next notice: Screenshot 1: Chrome debugger notice.

Register.js

<form onSubmit={ () => this.props.handleSubmit(this.state) }>
      <label>
        <span>Username *</span>
        <input
          type="text"
          name="username"
          onChange={ this.handleChange }
        />
      </label>

      <button>Sign in</button>
    </form>

Chat.js

<form onSubmit={ () => this.props.handleSubmit(this.state) }>
      <label>
        <input
          type="text"
          onChange={ this.handleChange }
        />
      </label>

      <button>Send message</button>
    </form>

Each form is being prevented from submitting as followed:

handleSubmit = ({ message }) => {
...
this.socket.send(JSON.stringify(data))

event.preventDefault()

}

This issue is making the page reload and adds the message to the query parameters: http://localhost:8080/?chat=it+is+refreshing

If i use a different approach and stop using the form element, it works.

Upvotes: 0

Views: 896

Answers (1)

MEnf
MEnf

Reputation: 1512

When you submit your form, you have to use e.preventDefault(), otherwise it will cause your page to reload when your form is submitted.

Change onSubmit={ () => this.props.handleSubmit(this.state) } to onSubmit={ (e) => e.preventDefault();this.props.handleSubmit(this.state) }

Or add a function that your form's onSubmit function calls like so:

handleSubmitForm = e => {
  e.preventDefault();
  this.props.handleSubmit(this.state)
} 

Upvotes: 1

Related Questions