Search code examples
reactjscomboboxheadless-ui

Set display value to empty when open - HeadlessUI Combobox


I'm new to React. I got a question regarding Combobox of HeadlessUI.

How do we set the value to empty when combobox is open? I'm trying to follow this autocomplete pattern below. When the options are opened, the input value is set to empty, so user can type straight away.

enter image description here

This is from existing example of Combobox, see that the input value is not empty when options are opened

enter image description here

What I have tried so far is to checking the open state of combobox inside displayValue, but it didn't work. The open is definitely not matched with the current open state. I believe because the function store the previous value of open.

<Combobox.Input                
  displayValue={(person) => {
    console.log("open", open);

    if (open) {
      return "";
    }

    return person.name;
  }}
  onChange={(event) => setQuery(event.target.value)}
/>

Here is my CodeSandbox.

I noticed we have two render props for Combobox.Input which are open and disabled. How to use that prop?

Thank you


Solution

  • Try to add key props to your Combobox.Input, it should work

    <Combobox.Input
      key={open}               
      displayValue={(person) => {
        if (open) {
          return "";
        }
    
        return person.name;
      }}
      onChange={(event) => setQuery(event.target.value)}
    />