Reputation: 188
I have a component, which is sending as a prop a method to change the forms input value (like any basic form). after having the onChange working, I decided to add a clear button to clear all input values at once, therefore I created a method to clear all inputs.
Example:
class ComponentName extends Component {
constructor(props) {
super(props);
this.state = {
formInputs: {
inputOne: "",
inputTwo: "",
inputThree: ""
}
};
};
handleOnChange = (event) => {
const { target: { name, value } } = event;
this.setState(previousState => {
return { formInputs: { ...previousState.formInputs, [name]: value } };
});
};
clearInputs = () => {
/* this is problematic, because I'm setting the input from defined to undefined */
this.setState({ formInputs: {} });
};
render() {
const { formInputs } = this.state;
return (
<Form
handleOnChange={this.handleOnChange}
clearInputs={this.clearInputs}
formInputs={formInputs}
/>
);
};
};
clearing like the method above is gonna give an error, because I'm removing the keys within state, which the form inputs have their values aimed to. no problem so I thought, I would just add all inputs within setState to equal an empty string like this: this.setState({ formInputs: { inputOne: "", inputTwo: "", inputThree: ""} });
which works. but I have a lot of inputs which have to be cleared, so probably that method is not the most efficient either. that being said, is there a more efficient way to clear each within the "formInputs" object in state?
Upvotes: 0
Views: 44
Reputation: 111
You can define the initial state in a separate variable outside the component(or inside if you like) and use it not only to initialize the state but also to reset the state to it inside the clearInputs
function.
Upvotes: 1