reactjsmaterial-uireact-material-ui-form-validator

How to get and set Autocomplete Multiple values?


I following this guild made a textfield. But i can not got this field value, Any suggestions?

https://mui.com/material-ui/react-autocomplete/#multiple-values

 const categories = [
   {id:1, name: "blog"},
   {id:2, name: "music"},
   {id:3, name: "video"},
]
 const [category, setCategory]: any = useState([]);

 <Autocomplete
                                            multiple
                                            limitTags={1}
                                            value={category}
                                            onChange={(event, newValue) => {
                                                setCategory([
                                                    ...category,
                                                    newValue
                                                ]);
                                            }}
                                            id="category-filter"
                                            options={categories}
                                            getOptionLabel={(option) => option.name}
                                            renderInput={(params) => (
                                                <TextField {...params} label="Category" placeholder="categories" />
                                            )}

                                        />

Solution

  • The newValue in onChange handler is already an array of selected options, so you can just set it into the category simply.
    Also since each option is an object, you have to add isOptionEqualToValue attribute to tell the component how to compare the option to the selected value. The code is as follows:

    import { useState } from "react";
    import { Autocomplete, TextField } from "@mui/material";
    
    export const Test = () => {
      const categories = [
        { id: 1, name: "blog" },
        { id: 2, name: "music" },
        { id: 3, name: "video" }
      ];
      const [category, setCategory] = useState([]);
      return (
        <Autocomplete
          multiple
          limitTags={1}
          value={category}
          onChange={(event, newValue) => {
            setCategory(newValue);
          }}
          id="category-filter"
          options={categories}
          getOptionLabel={(option) => option.name}
          isOptionEqualToValue={(option, value) => option.id === value.id}
          renderInput={(params) => (
            <TextField {...params} label="Category" placeholder="categories" />
          )}
        />
      );
    };