Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.sstatic.net/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?

like image 917
Darkbound Avatar asked Oct 18 '25 13:10

Darkbound


1 Answers

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
        }}

      />
like image 120
Madhuri Avatar answered Oct 20 '25 03:10

Madhuri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!