Home > front end >  Is it possible for MUI autocomplete to be linked with two field values?
Is it possible for MUI autocomplete to be linked with two field values?

Time:01-19

Hi I am trying to make a custom search input where user could click on it and be shown the possible filter categories they could select. Also they can optionally type a title keyword to then search with the title and the categories filter selected. A very good example of what I am trying to do is the telegram bugs website search bar. https://bugs.telegram.org/

So i was thinking of using mui autocomplete where when user selects the category it will populate some field state called categories containing an array of selected category. Then when the user types a custom text it will then be stored in keyword field. Is it even possible to do so? If not is there a better approach to do this.

CodePudding user response:

You can achieve this with the help of multiple, freeSolo and filterSelectedOptions props. I have made a working example similar to your case, You can find it here

import { useState } from 'react';
import Autocomplete from '@mui/material/Autocomplete';
import TextField from '@mui/material/TextField';

const options = [{ value:'1', label:'One'}, { value:'2', label:'Two'}, { value:'3', label:'Three'},];

export default function App() {
  const [selectedOptions, setSelectedOptions] = useState([]);

  return (
      <Autocomplete
        multiple
        freeSolo
        filterSelectedOptions
        options={options}
        onChange={(_, value) => {
           setSelectedOptions(value);
         }}
        renderInput={(params) => (
          <TextField
            {...params}
            label="Multiple values"
            placeholder="Add value"
         />
      )}
   />
 );
}

CodePudding user response:

Yes, it is possible to use Material-UI's Autocomplete component to achieve the functionality you described. You can set the options prop to the array of filter categories, and the renderInput prop to a custom input component that includes both the Autocomplete and the keyword input. When a user selects a category from the Autocomplete, you can update the categories state field with the selected value. When a user types in the keyword input, you can update the keyword state field with the entered text.

You may also consider using other libraries like react-select or downshift which provide similar functionality and are more flexible to customize.

  • Related