final-form / react-final-form-arrays

A component for rendering and editing arrays 🏁 React Final Form
MIT License
205 stars 70 forks source link

Loosing Focus While Typing On Custom Input Field #154

Open vivekcontentstack opened 3 years ago

vivekcontentstack commented 3 years ago

I'm using custom component to show the text input field nothing fancy just the basic component

const CustomTextField = ({ ...rest }) => {
  return <input {...rest} />;
};

When I'm trying to using this component inside react-final-form-array for some reason I'm loosing the focus when typing on the input field, I guess its because of the re-rendering.

<Field
    name={`${name}.lastName`}
    component={({ input, meta, ...rest }) => {
      return (
        <CustomTextField {...input} type="text" {...rest} />
      );
    }}
    placeholder="Last Name"
  />

here is the link to the full code on codesandbox

As you can see the "First Name" works fine but the "Last Name" loosing focus while typing.

How can I fix this issue, any help is appreciated

Thanks

tjb042 commented 3 years ago

@vivekcontentstack I believe this is because you're passing an inline function into the component prop. The component prop is using React.createElement to create the new element under the hood. That means if you provide an inline function to the component prop, you would create a new component every render. To resolve this, remove the inline function from the component prop and set it as children.

In this case your code above could change to:

<Field name={`${name}.lastName`} placeholder="Last Name">
    {({input, meta, ...rest}) => (
        <CustomTextField {...input} type="text" {...rest} />
    )}
</Field>