Hi, there
I want to save the input value from handleChange and when I click submit button, console will show the data I received from form in the form of an object. However, the handleChange saved every value when I type in. How can I fix it? Please help!
You might want to paste the entire code for the App
component (including the body of render()
). Pasting the text itself is preferable to pasting a screenshot.
class App extends Component {
constructor() {
super();
this.state = {
bmiReferenceProps,
userInfo: [],
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleChange({ target }) {
const newInfo = { [target.id]: target.value };
this.setState({ userInfo: [...this.state.userInfo, newInfo] });
/*this.setState(
{userInfo: { [target.id]: target.value }}
);*/
}
handleSubmit(event) {
console.log(JSON.stringify(this.state.userInfo));
event.preventDefault();
}
render() {
return (
<div className="main">
<form onSubmit={this.handleSubmit}>
<h1>{bmiReferenceProps.observationName}</h1>
{bmiReferenceProps.dataElements.map((form) => {
if (form.type === 'textInput') {
return (
<TextInput
key={form.id + 1}
id={form.id}
displayName={form.displayName}
isRequired={form.isRequired}
display={form.display}
handleChange={this.handleChange}
/>
);
}
if (form.type === 'numberInput') {
return (
<NumInput
key={form.id + 1}
id={form.id}
displayName={form.displayName}
isRequired={form.isRequired}
unitOfMeasure={form.unitOfMeasure}
handleChange={this.handleChange}
max={form.bounds.upperLimit}
display={form.display}
/>
);
}
if (form.type === 'select') {
return (
<DropdownSelect
key={form.id + 1}
id={form.id}
displayName={form.displayName}
isRequired={form.isRequired}
options={form.options}
display={form.display}
handleChange={this.handleChange}
/>
);
}
})}
<input id="submit" type="submit" value="Submit" />
</form>
</div>
);
}
}
export default App;
How about adding a new state variable for the user input? Then update that in handleChange
instead of immediately updating userInfo
with a new array. You probably mean to update userInfo
in the handleSubmit
function.
I’m sorry that I’m confused. I thought the const newInfo is a variable that be used for save the state of user input? how to not immediately updating userInfo?
newInfo
is only a regular variable. Its value is discarded after handleChange
finishes running. It’s not recognized by React as a state variable.
If you only meant to update userInfo
when the form is submitted, then you should move the code that sets its value from handleChange
to handleSubmit
. Then you’ll need a new state variable to hold the user input, then update its value in handleChange
. You can then access that in handleSubmit
when updating userInfo
.
Got it! Thank you!