Raissa Correia
Raissa Correia

Reputation: 169

Material-UI AutoComplete freeSolo in Form

https://codesandbox.io/s/naughty-bogdan-hvhsd?file=/src/searchfield.tsx

As you can see in this SandBox, I'm using Material AutoComplete as a multiple input with free options. The component should return to Formik ["term1","term2","term3"] and the user can see each string as a label in a Chip. This will be used as filters in a search. This all happens, but only if the input is already in InitialValues. If the user does an input manually and press enter or tab it craches in a error "value.map" is not a function. The error points to this line in the material autocomplete component code

"getInputProps = _useAutocomplete.getInputProps,"

Does anyone has any ideia on how to make AutoComplete and Forms work together?

Upvotes: 2

Views: 3576

Answers (1)

Arthur Rubens
Arthur Rubens

Reputation: 4706

Something like this (searchfield.tsx):

import React, { useState } from "react";
import { TextField } from "@material-ui/core";
import { Formik, Form } from "formik";
import Autocomplete from "@material-ui/lab/Autocomplete";

export default function SearchBar() {
  const [searchValues] = useState(["ola", "como"]);

  return (
    <Formik
      initialValues={{
        search: []
      }}
      onSubmit={(values, { setSubmitting }) => {
        setTimeout(() => {
          JSON.stringify(values, null, 2);
          console.log(values);
          setSubmitting(false);
        }, 400);
      }}
    >
      {({ values, handleChange, handleBlur, handleSubmit }) => (
        <Form onSubmit={handleSubmit}>
          <Autocomplete
            autoSelect
            freeSolo
            id="search"
            limitTags={4}
            multiple
            onBlur={handleBlur}
            onChange={handleChange}
            options={searchValues}
            getOptionLabel={option => option}
            filterSelectedOptions
            renderInput={params => (
              <TextField
                {...params}
                id="search"
                name="search"
                variant="outlined"
                label="Busca"
                placeholder="Termos de Busca"
              />
            )}
          />
          <h6>{searchValues}</h6>
        </Form>
      )}
    </Formik>
  );
}

Upvotes: 4

Related Questions