I'm creating a form where I want to add form rows and edit any row/cell at any time. It seems to work fine by adding new rows but if I edit a previous row/cell the form fields get's messed up.
This is my handleChange for each field:
handleChange = (key, e) => {
const { name, value } = e.target
const currentRow = this.state.formRows.filter(r => r.key === key)[0]
const withoutCurrentRow = this.state.formRows.filter(r => r.key !== key)
const updatedRow = { ...currentRow, [name]: value }
const newRows = [...withoutCurrentRow, updatedRow]
this.setState(({ formRows }) => ({ formRows: newRows }))
}
Here's my form on codesandbox
You are passing in the arguments in wrong order for one of your inputs. It should be the key
as first argument and the event
as second.
<Input
value={description}
name="description"
placeholder="description"
style={{ width: '20%', marginRight: 8 }}
onChange={e => this.handleChange(key, e)}
/>
<Input
value={amount}
name="amount"
placeholder="amount"
style={{ width: '20%', marginRight: 8 }}
onChange={e => this.handleChange(key, e)}
/>
You could also use findIndex
to get the index of the object you want to update, and create a new copy of that object in the array with an updated field.
handleChange = (key, e) => {
const { name, value } = e.target;
this.setState(previousState => {
const formRows = [...previousState.formRows];
const currentIndex = formRows.findIndex(row => row.key === key);
formRows[currentIndex] = { ...formRows[currentIndex], [name]: value };
return { formRows };
});
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.