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>
);
}