Can't get my form in React to work properly

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Can't get my form in React to work properly



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 updating the row and appending it to last of newRows, you have to maintain the index of the updated row.
– cheekujha
Aug 6 at 10:48




1 Answer
1



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.


key


event


<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.


findIndex


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 ;
);
;





Thanks for this. Your solution works well. Just wondering what is the main bug in my code. I'm taking a bit different approach and setting the state after the new one is already created...
– karolis2017
Aug 6 at 11:02





@karolis2017 You're welcome! You filter out the object you want to update and then add it back again at the end of the array. You want to preserve the order of the objects in the array so the inputs don't change order when rendered.
– Tholle
Aug 6 at 11:05






Got it now. Thanks again
– karolis2017
Aug 6 at 11:09





@karolis2017 Great! Consider upvoting my answer. That would make me happy.
– Tholle
Aug 6 at 11:38







By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

make 2 or more post in bootsrap

Store custom data using WC_Cart add_to_cart() method in Woocommerce 3

Firebase Auth - with Email and Password - Check user already registered