Reputation: 103
I have a component with state like. I am creating dynamic form, all is working fine but I want to reset the form value once submit button clicked. for that i have a helper function called resetForm() , but unfortunately the logic is not working. can anybody help with this..
state = {
expenseForm: {
date: {
elementType: 'input',
elementConfig: {
type: 'date',
placeholder: 'Enter Date..'
},
value: '',
validation: {
required: true,
isDate: true
},
valid: false,
touched: false
},
category: {
elementType: 'select',
elementConfig: {
options: !this.props.loading ? transformCategory(this.props.categories): null
},
value: transformCategory(this.props.categories)[0].value,
validation: {
required: true,
minLength: 4
},
valid: true,
touched: false
},
description: {
elementType: 'input',
elementConfig: {
type: 'text',
placeholder: 'Enter Description..'
},
value: '',
validation: {
required: true,
minLength: 6
},
valid: false,
touched: false
},
amount: {
elementType: 'input',
elementConfig: {
type: 'number',
placeholder: 'Enter amount..'
},
value: '',
validation: {
required: true,
minLength: 1
},
valid: false,
touched: false
}
},
formIsValid: false
}
Upvotes: 1
Views: 400
Reputation: 112777
You could have a function getInitialState
that returns an object you can use as initial state for your component. When you need to reset the component state, you can use setState
with the result of getInitialState
again.
Example
function getInitialState() {
return {
email: "",
password: ""
};
}
class App extends React.Component {
state = getInitialState();
onChange = event => {
this.setState({ [event.target.name]: event.target.value });
};
resetForm = () => {
this.setState(getInitialState());
};
render() {
const { email, password } = this.state;
return (
<div>
<div>
Email: <input name="email" value={email} onChange={this.onChange} />
</div>
<div>
Password: <input name="password" type="password" value={password} onChange={this.onChange} />
</div>
<button onClick={this.resetForm}> Reset </button>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Upvotes: 1