'Append a button at the end of Autocomplete options in Material-UI

I am trying to create an autocomplete component that a person will use to select an item from a list of items, I've done that, no issues.

The problem is thatI also want to add a button at the end of the list (like a last item in the list that is always present), so that if the item that the person is looking for is non existent the person can click that button to add a new item. This is the same question and is answered but for react-select, I cant find anything in the API of material-ui to do the same. Append a button at the end of options in react-select

An example (taken from the question above): https://i.stack.imgur.com/WRFd8.png

I tried adding an onClick to the TextField, but of course, that gets triggered as soon as someone clicks on the auto ocmplete

  <Autocomplete
    id="supplierIdd"
    style={{ width: 300 }}
    options={suppliers.map((supplier) => supplier.name)}
    renderInput={(params) => 
      <>
        <TextField {...params} label="Булстат" margin="normal" onClick={()=>{console.log("hi")}} variant="outlined" />
      </>
    }
  />

I also tried adding to the options array, but of course that is an array of just options, not elements, so where would I add a or whatever element?



Solution 1:[1]

I found solution, You can use "filterOptions" method to add a new button at the bottom.

Check this::

<Autocomplete
    id="supplierIdd"
    style={{ width: 300 }}
    options={suppliers.map((supplier) => supplier.name)}
    renderInput={(params) => 
      <>
        <TextField {...params} label="???????" margin="normal" onClick={()=>{console.log("hi")}} variant="outlined" />
      </>
    }
    filterOptions={(options) => {
          const result = [...options]
          result.push(
            ((
              <Button
                variant="outlined"
                color="primary"
                onMouseDown={onAddNew}
              >
               + Add New
              </Button>
            ) as unknown) as string,  // typecasting required for typescript
          )

          return result
        }}

      />

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Madhuri