I have a react form. The user fills out the form and submits the form but there is an error when submitting. The error is displayed. When the user hits the reset button, I would like that error to disappear. How do I do that? So once the user resets the form, I would like the form to be new. I have included all the code.
Here's my code:
class VehiclePage extends React.Component{
defaultState = { errors: [], tag: null, vin: null, location: null, message:
null, msg: null};
constructor(props){
super(props);
this.state=this.defaultState;
this.submitVehicle=this.submitVehicle.bind(this);
this.resetFromState=this.resetFromState.bind(this);
this.validateForm = this.validateForm.bind(this);
}
resetFromState= ()=>{
this.setState({
...this.defaultState});
}
validateForm(tag, vin, location){
const errors=[];
if (tag==''){
errors.push("Please enter vehicle's RFIDTAG.");
}else if (vin==''){
errors.push("Please enter the vehicle's VIN.");
}else if(vin.length<17){
errors.push("VIN must be longer than 17 characters.");
}else if(location==''){
errors.push("Please enter vehicle's location.");
}
return errors;
}
submitVehicle(tag, vin, location){
let msg;
let errors=this.validateForm(tag, vin, location);
console.log("tag:", tag);
if(errors.length>0){
this.setState({errors: errors});
console.log("error: ", errors);
return;
}else{
this.setState({errors: []});
var input={
rfidtag: tag,
vin: vin,
vehzone: location
};
console.log("the object is: ", input);
this.props.createVehicle(input);
if(this.props.message != ''){
console.log("SERVER ERROR!!!");
}
}
}
render(){
const {errors} = this.state;
return(
<div>
<AddVehicle submitVehicle={this.submitVehicle}
resetFromState={this.resetFromState} />
<div><font color="red">{errors}</font></div>
<h4>{this.props.message}</h4>
</div>
)
}
}
const mapStateToProps=(state, ownProps) => {
console.log("state in vehicle page is: ",state);
return{
vehicle: state.vehicle,
message: state.vehicleReducer.message,
error: state.vehicleReducer.error
}
};
const mapDispatchToProps=(dispatch)=>{
return {
createVehicle: vehicle =>
dispatch(vehicleActions.createVehicle(vehicle))
}
};
export default connect(mapStateToProps, mapDispatchToProps)(VehiclePage);
Figured out how to do it. I created an action called reset and called it when the reset button was pressed.
To reset your form you'll need to add the
value
attribute to your from elements likeinput
Then when you want to reset them, set them back to their default value