Reputation: 115
I have followed the tutorial from an article written by Formik Team member But things are not working as expected; whenever I type something in the text input field, on each key press it lost focus, again and again, I have to click on the text input field to write next character. I have shared codesandbox link.
here is the code is taken from the article
import React from 'react';
import { Formik, Form, Field, FieldArray } from 'formik';
export const InviteFriends = () => (
<div>
<h1>Invite Friends</h1>
<Formik
initialValues={{ friends: ['', '', ''] }}
onSubmit={values => alert(values)}
render={formikProps => (
<Form>
<Field name="email" />
<FieldArray
name="friends"
render={({ remove, push }) => (
<>
{formikProps.values.friends.map((friend, i) => (
<div key={`friend-${i}-${friend}`}>
<Field name={`friends[${i}]`} type="email" />
<button type="button" onClick={() => remove(i)}>
X
</button>
</div>
))}
<button type="button" onClick={() => push('')}>
Add friend
</button>
</>
)}
/>
<button type="submit">Invite Friends</button>
</Form>
)}
/>
</div>
);
Upvotes: 6
Views: 6138
Reputation: 424
in other case the bug exist when the component and logic are in component props from Field component example :
....
<Field name=... component={({field, form}) => <MyComponent onChange={(e) => form.setFieldValue} />}
<Field name=... component={({field, form}) => <MyComponent2 onChange={(e) => form.setFieldValue} />}
<Field name=... component={({field, form}) => <MyComponent3 onChange={(e) => form.setFieldValue} />}
here, formik lost the state, the solution is :
<Field name=... component={MyComponent}
<Field name=... component={MyComponent2}
<Field name=... component={MyComponent3}
And like this, the formik functions is directly in component, we give just reference component and keep all values and all focus !!!
Upvotes: 0
Reputation: 206
The issue in your code is in key property template: key={'friend-${i}-${friend}'}
. This key should be permanent for the same component when props change. However, in your case it includes ${friend}
which means the key changes with each key stroke.
Solution: Just remove ${friend}
from your key to make it constant for the same item.
Upvotes: 19