Input loses focus when using custom input for Formik Field in FieldArray

Asked
Active3 hr before
Viewed126 times

8 Answers

fieldfocusinput
90%

Try to type something into the Email address field. You should see that the input loses focus after typing a character,So in our project we are using a component that is coming from our storybook. The component in storybook accepts either a string or a JSX Element,I expect to be able to keep typing into the field, without it losing focus.

const Input = styled(FormikField)`
    background: ${({ hasError }) => (hasError ? red100 : shades100)};
    border: none;
    border-radius: 0.25rem;
    height: 2.5rem;
    padding-left: 0.5rem;
    width: 100%;
`;

const FormInputWithError = (props: any) => {
  return <Input {...props} />;
};
load more v
88%

Here is the form setup:,I am using custom input components to handle my form data, and noticed strange behaviour. Only when I am using FieldArray with custom input components the input loses focus as I type. ,Is there another way I have to use custom inputs for FieldArray? I do not experience this problem when I am not using FieldArray.

Pretag
 Pretag team - issue, fix, solve, resolve
72%

A custom React component,Either a React component or the name of an HTML element to render. That is, one of the following:,component can either be a React component or the name of an HTML element to render. All additional props will be passed through.

1 import React from 'react';2 import { Field, Form, Formik, FormikProps } from 'formik';3 4 const MyInput = ({ field, form, ...props }) => {5   return <input {...field} {...props} />;6 };7 8 const Example = () => (9   <div>10     <h1>My Form</h1>11     <Formik12       initialValues={{ email: '', color: 'red', firstName: '', lastName: '' }}13       onSubmit={(values, actions) => {14         setTimeout(() => {15           alert(JSON.stringify(values, null, 2));16           actions.setSubmitting(false);17         }, 1000);18       }}19     >20       {(props: FormikProps<any>) => (21         <Form>22           <Field type="email" name="email" placeholder="Email" />23           <Field as="select" name="color">24             <option value="red">Red</option>25             <option value="green">Green</option>26             <option value="blue">Blue</option>27           </Field>28 29           <Field name="lastName">30             {({31               field, // { name, value, onChange, onBlur }32               form: { touched, errors }, // also values, setXXXX, handleXXXX, dirty, isValid, status, etc.33               meta,34             }) => (35               <div>36                 <input type="text" placeholder="Email" {...field} />37                 {meta.touched && meta.error && (38                   <div className="error">{meta.error}</div>39                 )}40               </div>41             )}42           </Field>43           <Field name="lastName" placeholder="Doe" component={MyInput} />44           <button type="submit">Submit</button>45         </Form>46       )}47     </Formik>48   </div>49 );
load more v
65%

Try to type something into the Email address field. You should see that the input loses focus after typing a character, Ask questionsCustom field component loses focus when typing a single character ,I expect to be able to keep typing into the field, without it losing focus.

Pretag
 Pretag team - issue, fix, solve, resolve
75%

📋 Custom React hooks for form validation without the hassle,Spectrum will become read-only on August 24, 2021. Learn more about the decision in our official announcement.

<Controller    as={<TextField        error={!!errors?.GeneralInfo?.name}        helperText={errors?.GeneralInfo?.name.message}        label="Name"        style={{width: "100%"}}    />}    control={control}    defaultValue={''}    name="GeneralInfo.name"/>
<TextField    defaultValue={''}    error={!!errors?.GeneralInfo?.name}    helperText={errors?.GeneralInfo?.name.message}    inputRef={register}    label="Name"    name="GeneralInfo.name"    style={{width: "100%"}}/>
load more v
40%

When I type something in my custom field it loses focus and needs to be clicked again in order to add data, Below is the sandbox link to code. It only happens when I pass error and touched props to check for validation, If I remove that it works perfectly.,I needed to set line 147 to any as i couldn't get the types to behave so any help there would be nice.,I would see this as a bug, that forces the use of workarounds. In my personal opinion undefined should be equal to a non existing value.

I tried adding trim() to my formik validation schema:

Yup.object().shape({
   label: Yup.string().trim().required('some error msg'),
});
load more v
22%

Demonstrates how to use the formatOnBlur prop to postpone the formatting of a form field value until the field loses focus. Very useful for formatting numbers, like currencies.,Demonstrates how to use a 🏎️ Downshift type-ahead component as an input.,Demonstrates how fields can be grouped into reusable components.

Pretag
 Pretag team - issue, fix, solve, resolve
60%

Briefly, the "name" input will lose focus every time its :on-change event is dispatched. This happens because the handler creates a new value for the external-input state, which sparks the re-rendering of the whole foo component.,The field-array-fn must be a different reagent component to avoid the inputs focus loss. A comprehensive example of the fieldarray functionality can be found here.,What follows is a list of the fieldarray available handlers:

Pretag
 Pretag team - issue, fix, solve, resolve

Other "field-focus" queries related to "Input loses focus when using custom input for Formik Field in FieldArray"