ReactJS – Page refreshing upon onClick of a button

Hey Guys!

Today was one of those days where I encountered a weird problem. It took me a while to figure it out. In this blog, I’ll share what the issue was and how I finally solved it. It sounds like an easy fix, but it definitely took some time to sort out!

Problem

We had the below lines of code

<form>
        <label for="fname">FirstName: </label>
        <input
          id="fname"
          type="text"
          value={this.state.firstName}
          onChange={this.firstNameChange}
        />
        <br />
        <br />
        <label for="lname">LastName: </label>
        <input
          id="lname"
          type="text"
          value={this.state.lastName}
          onChange={this.lastNameChange}
        />
        <br />
        <br />
        <label for="email">Email: </label>
        <input
          id="email"
          type="email"
          value={this.state.email}
          onChange={this.emailChange}
        />
        <br />
        <br />
        <label for="contact">Contact: </label>
        <input
          id="contact"
          type="text"
          value={this.state.contact}
          onChange={this.contactChange}
        />
        <br />
        <br />
        <button onClick={this.submit}>Submit</button>
 </form>

We encountered an issue with our form where clicking the Submit button caused the entire page to refresh. This behavior was unexpected and disrupted the user experience. It was both puzzling and inconvenient to deal with.

Solution

I explored various blogs and StackOverflow answers. During my research, I discovered a surprisingly simple fix for this issue. After investigating further, I discovered the root cause was the <button> tag. Without the type attribute, it was defaulting to a submit button, triggering the page refresh. Adding the appropriate type attribute resolved the issue instantly. It’s amazing how such a minor detail can create such unexpected behavior! 🤯

Yea it sounds simple, but it killed my time

// solution 1

<button type="button" onClick={this.submit}>Submit</button>

There’s also one more solution. Instead of having the click event handler in the button, you can mention it in the <form> attribute

// solution 2

<form onSubmit={this.submit}>
    ....
    ....
    ....
    <button type="submit">Submit</button>
</form>

Root cause

By default, buttons without a specified type are treated as submit buttons in forms. This leads to automatic page refreshes when clicked.

I hope this will be useful!

Happy Coding! Cheers

Leave a comment

Blog at WordPress.com.

Up ↑