Jackson Lenhart Jackson Lenhart - 3 months ago 31
React JSX Question

ReactJS bootstrap form without refreshing page

I have a form in my very basic React app where I want to allow the user to enter text and create their username by updating state. However when the "OK" button is clicked, the created username appears on the page for about half a second then the page auto-refreshes and restores the default state. It only happens when the button is contained within a form element. It works fine and the page doesn't refresh when I remove the form element, however I don't want to sacrifice the style and formatting of the bootstrap form. Here's my render method:

render() {
return (
<div class="container-fluid text-center">
<form class="form-inline">
<input type="text" class="form-control" placeholder="UserName"/>
<button onClick={this.createUser.bind(this)} class="btn btn-primary">OK</button>
<h1>User: {this.state.userName}</h1>
<h1>Points: {this.state.points}</h1>


Your button doesn't have a type attribute, so the default will be submit (see this page). This means that when you click your button the onClick handler will be called, but the default browser action of submitting the form will also happen.

Try specifying a type of button instead:

<button type="button" onClick={this.createUser.bind(this)} class="btn btn-primary">OK</button>

Also, if you don't specifically need a form element you could try changing it to a <div>. The bootstrap form-inline style doesn't require a form, as mentioned in the documentation under the Inline form heading:

Add .form-inline to your form (which doesn't have to be a <form>)...