My Name is Ratna
My Name is Ratna

Reputation: 113

React MUI Formik Input loses focus after typing

I am using React with MUI and Formik to create a form, but after I typed a character on the input field, it loses focus. I indeed wrapping each input field in a component so that it can be reusable many times as a cleaner code. But it turns out it loses focus everytime onchange rerenders.

What I've done so far:

Here is my live demo code: https://codesandbox.io/s/condescending-resonance-5r5nv?file=/src/Form.js

Any clues is greatly appreciated. Thanks in advance.

import { Form, FormikProvider, useFormik, FieldArray } from "formik";
import { TextField, Button, Stack } from "@mui/material";
import uuid from "react-uuid";

export default function FormComponent() {
  const formik = useFormik({
    enableReinitialize: false,
    initialValues: {
      name: "Jordan Spikes",
      description: "Just a regular dude",
      state: "Alabama",
      country: "USA"
    }
  });

  const { handleSubmit, getFieldProps } = formik;

  const FieldStack = (props) => (
    <Stack
      key={uuid()}
      direction={{ xs: "column", md: "row" }}
      sx={{ mb: 3 }}
      spacing={2}
    >
      <TextField
        fullWidth
        label={props.name}
        {...getFieldProps(`${props.data}`)}
      />
    </Stack>
  );

  return (
    <FormikProvider value={formik}>
      <Form autoComplete="off" noValidate onSubmit={handleSubmit}>
        <h3>Form</h3>
        <FieldStack name="Name" data="name" />
        <FieldStack name="Description" data="description" />
        <FieldStack name="State" data="state" />
        <FieldStack name="Country" data="country" />
      </Form>
    </FormikProvider>
  );
}

Upvotes: 2

Views: 1651

Answers (1)

Volodymyr Ivanenko
Volodymyr Ivanenko

Reputation: 48

Use stable key variable in Stack element. It should not be changed in every render.

<Stack
  key={**use array index or any other stable variable**}
  direction={{ xs: "column", md: "row" }}
  sx={{ mb: 3 }}
  spacing={2}
>
  <TextField
    fullWidth
    label={props.name}
    {...getFieldProps(`${props.data}`)}
  />
</Stack>

Upvotes: 1

Related Questions