Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formik FieldArray lost focus when "onChange" triggered

Tags:

reactjs

formik

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>
);
like image 680
nouman Avatar asked Sep 27 '18 07:09

nouman


1 Answers

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.

like image 188
Aliaksei Ivaneichyk Avatar answered Sep 24 '22 19:09

Aliaksei Ivaneichyk