How to add a clear button to the auto complete field in material-ui

11,335

Working Pen: https://codepen.io/pranesh-r/pen/yawzbW?editors=0010

Consider using a controlled component here. Set the user input to the state using onUpdateInput event and pass the value in the state to the <AutoComplete/> using searchText props. When the user clicks clear button, clear the input in the state.

P.S. I've used FlatButton as the clear. You can also use IconButton.

Hope this helps!

Share:
11,335
mlemler
Author by

mlemler

Updated on June 07, 2022

Comments

  • mlemler
    mlemler about 2 years

    I am using Material-UIs AutoComplete Component (v0.15.4) to implement kind of a filter. To improve the user experience I want to add a clear button (Icon Button component?) inside or next to it which simply clears the current input (like in the pictures of the Google Specification for Auto-complete text fields).

    Since the AutoComplete uses the TextField, I thought of giving an ListItem or MenuItem to the "value" of the TextField and use the rightIcon(Button). But the AutoComplete only allows String as "SearchText" (whic internaly is uses to fill the "value" field of the TextField).

    So since I can not put an other component inside the "searchText" I end up with the idea of wrapping the AutoComplete inside a ListItem like this:

    <ListItem
      primaryText={<AutoComplete
        dataSource={ dataSource }
        filter={AutoComplete.fuzzyFilter}
        hintText="Select Filter"
        onNewRequest={this.handleSelect.bind(this)} />}
      rightIconButton={<IconButton
        onClick={this.handleClearClick.bind(this)}>
          <ClearIcon />
        </IconButton>}
    />
    

    But this way the clear icon appears behind the auto complete input field and I do not really need/want the list (item).

    Are there any other idea of solving this problem? Or is maybe the clear-function (or more generic "rightIconButton" field) planed for future version of Material-UI?

  • mlemler
    mlemler over 7 years
    Hi Pranesh, thanks for the proposal. I tried this one before and it works but only if the user really types something in the field. But when I also set openOnFocus={true} (I seem to forgot this above) and the user clicks on an entry from the list (without typing any letter) the onUpdateInput is not triggered and therefore the state does not change which causes the button not to work because it also does not change the state.
  • Arslan Tariq
    Arslan Tariq over 7 years
    I was having the same issue. Could not clear the field. It worked by the solution you have provided. Thanks! I had been pulling my hair off for some hours.