This is a ReactJS Problem.
I can't reset multiple input fields of a form.
There is a form in my app that has multiple input fields, I use an onChange function to grab the user inputs, then update this.state with setState, then I copy all the values from this.state with a spread operator and create a new object storing those copied values. Lastly, I pass the new object into a function for further use (not relevant). My code problem is I can't empty the fields after passing the object into a function. I tried manually resetting the values by clearing the values with this.setState, as well as event.target.reset(), but both don't work.
import React, { Component } from "react";
class AddFishForm extends Component {
// Controlled state
state = {
name: "",
price: "",
status: "available",
desc: "",
image: ""
};
// Step 1: onChange: Update this.state
updateFishState = event => {
const { name, value } = event.target;
this.setState({
[name]: value
});
};
// Step 2: onSubmit: Create Fish Object
createFish = event => {
// prevent refresh
event.preventDefault();
// copy values inside this.state and paste into new fish object
const fish = {
name: this.state.name,
price: parseFloat(this.state.price),
status: this.state.status,
desc: this.state.desc,
image: this.state.image
};
// pass new fish object into addFish() in App.js
this.props.addFish(fish);
// ! reset form (NOT WORKING) !
event.currentTarget.reset();
};
render() {
return (
<form className="fish-edit" onSubmit={this.createFish}>
<input
name="name"
value={this.state.name}
type="text"
placeholder="name"
onChange={this.updateFishState}
/>
<input
name="price"
value={this.state.price}
type="text"
placeholder="price"
onChange={this.updateFishState}
/>
<select
name="status"
// Value equals to whichever option is selected
value={this.optionsState}
onChange={this.updateFishState}
>
<option value="available">Fresh!</option>
<option value="unavailable">Sold Out!</option>
</select>
<textarea
name="desc"
value={this.state.desc}
type="text"
placeholder="Enter description..."
onChange={this.updateFishState}
/>
<input
name="image"
value={this.state.image}
type="text"
placeholder="image"
onChange={this.updateFishState}
/>
<button type="submit">Add Fish</button>
</form>
);
}
}
export default AddFishForm;
I expect the form to be cleared with "event.currentTarget.reset();", but the inputs lingers event after submitting the form. Help?