I'm trying to create an input form that stores information in a component's state variable, then outputs that variable on the screen. I read the docs on controlled components, and that's what I'm attempting here.
My main issue here is when I click submit, the correct text appears on the screen, but then the entire page refreshes and I'm not sure why. From what I've read online, refs
appear to be a solution, but my understanding is that I can use either that, or controlled components.
class InputField extends React.Component { constructor(props) { super(props); this.state = { itemName: "", storedItemName: "", }; this.handleNameChange = this.handleNameChange.bind(this); this.afterSubmission = this.afterSubmission.bind(this); } handleNameChange(event) { this.setState({ itemName: event.target.value }); } afterSubmission(event) { let name = this.state.itemName; this.setState ({ storedItemName:this.state.itemName }, function() { alert(this.state.storedItemName); // Shows the right value! }); } render() { return( <div> <form onSubmit = {this.afterSubmission}> <label> Item Name: <input type = "text" name = "itemName" value = {this.state.itemName} onChange = {this.handleNameChange} /></label> <input type = "submit" value = "Submit" /> </form> <div className = "itemList"> <p>Hi</p> {this.state.storedItemName} </div> </div> ); }
Use the preventDefault() method on the event object to prevent a page refresh on form submit in React, e.g. event. preventDefault() . The preventDefault method prevents the browser from issuing the default action which in the case of a form submission is to refresh the page.
The auto-refresh is triggered by the loading indicator (the spinner icon that you see in the top right part of the app bar). You can disable the auto-refresh by replacing the loading indicator by your own.
What preventDefault() does is that it tells the browser to prevent its default behaviour and let us handle the form submitting event on the client side itself.
Just call event.preventDefault
method to prevent default behavior of form
afterSubmission(event) { event.preventDefault(); let name = this.state.itemName; this.setState ({ storedItemName:this.state.itemName }, function() { alert(this.state.storedItemName); // Shows the right value! } }
Prevent the default behaviour:
afterSubmission(event) { event.preventDefault(); let name = this.state.itemName; this.setState ({ storedItemName:this.state.itemName }, function() { alert(this.state.storedItemName); // Shows the right value! }); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With