PauloZapo
PauloZapo

Reputation: 103

InitialValues are not displayed in AutoComplete from Material UI component in Formik Field

I have problem with rendering initialValues in AutoComplete component from Material UI library used in Formik Field. Values passed as initial are not rendered in component despite fact that if the form is submitted then they are passed in values variable.

I am also using material-ui-formik-components library if that fact matters.

Code shown below presents the issue.

import React from "react";
import { Formik, Form, Field } from "formik";
import { object, array } from "yup";
import { Autocomplete } from "material-ui-formik-components/Autocomplete";

const skills = [

  {
    "label": "PostgreSQL",
    "value": "PostgreSQL"
  },
  {
    "label": "Python",
    "value": "Python"
  },
  {
    "label": "React",
    "value": "React"
  },
  {
    "label": "Redis",
    "value": "Redis"
  },
  {
    "label": "Swift",
    "value": "Swift"
  },
  {
    "label": "Webpack",
    "value": "Webpack"
  }
]
const validationSchema = object().shape({
  skills: array().required("At least one skill is required")
});

const initialValues = {
  username: "",
  gender: "",
  country: "",
  skills: [
    {
      label: "PostgreSQL",
      value: "PostgreSQL"
    }
  ],
  birthdate: null
};

const SimpleFormExample = () => (
  <div>
    <h1>Simple Form Example</h1>
    <Formik
      initialValues={initialValues}
      validationSchema={validationSchema}
      validateOnBlur={false}
      validateOnChange
      onSubmit={values => {
        console.log(values);
      }}
    >
      {formik => (
        <Form noValidate autoComplete="off">
          <Field
            name="skills"
            options={skills}
            component={Autocomplete}
            textFieldProps={{
              label: "Skills",
              required: true,
              variant: "outlined"
            }}
            multiple
          />

          <button type="submit">Submit</button>
        </Form>
      )}
    </Formik>
  </div>
);

export default SimpleFormExample;

What should is do to display initialValues in formik?

Upvotes: 3

Views: 3021

Answers (1)

True
True

Reputation: 736

import React from "react";
import { Formik, Form, Field } from "formik";
import { object, array } from "yup";
import { Autocomplete } from "material-ui-formik-components/Autocomplete";
import { TextField } from "@material-ui/core";
import { fieldToTextField } from "formik-material-ui";

const skills = [
  {
    label: "PostgreSQL",
    value: "PostgreSQL"
  },
  {
    label: "Pythonaa",
    value: "Pythona"
  },
  {
    label: "React",
    value: "React"
  },
  {
    label: "Redis",
    value: "Redis"
  },
  {
    label: "Swift",
    value: "Swift"
  },
  {
    label: "Webpack",
    value: "Webpack"
  }
];
const validationSchema = object().shape({
  skills: array().required("At least one skill is required")
});

const initialValues = {
  username: "abc",
  gender: "",
  country: "",
  skills: [
    {
      label: "Swift",
      value: "Swift"
    },
    {
      label: "Webpack",
      value: "Webpack"
    }
  ],
  birthdate: null
};

const FormikAutocomplete = ({ textFieldProps, ...props }) => {
  const {
    form: { setTouched, setFieldValue }
  } = props;
  const { error, helperText, ...field } = fieldToTextField(props);
  const { name } = field;

  return (
    <Autocomplete
      {...props}
      {...field}
      onChange={(_, value) => setFieldValue(name, value)}
      onBlur={() => setTouched({ [name]: true })}
      getOptionSelected={(item, current) => item.value == current.value}
      renderInput={props => (
        <TextField
          {...props}
          {...textFieldProps}
          helperText={helperText}
          error={error}
        />
      )}
    />
  );
};

const SimpleFormExample = () => (
  <div>
    <h1>Simple Form Example</h1>
    <Formik
      initialValues={initialValues}
      validationSchema={validationSchema}
      validateOnBlur={false}
      validateOnChange
      onSubmit={values => {
        console.log(values);
      }}
    >
      {formik => (
        <Form>
          <Field
            name="skills"
            component={FormikAutocomplete}
            label="Skills"
            options={skills}
            textFieldProps={{
              fullWidth: true,
              margin: "normal",
              variant: "outlined"
            }}
            multiple
          />

          <button type="submit">Submit</button>
        </Form>
      )}
    </Formik>
  </div>
);

export default SimpleFormExample;

You can check my codesandbox https://codesandbox.io/s/optimistic-kare-9wqfq?file=/src/Component.tsx:0-2327

You can also change getOptionSelected prop of AutoComplete to determine if an option is selected or not.

Upvotes: 3

Related Questions