Search code examples
reactjsprimereact

How to show customized/formatted drop-down value in PrimeReact's AutoComplete?


Please see my full sandbox code for this question. I have a drop down using AutoCompete where the datasource is a list of countries. I format the drop down values using itemTemplate to add the word "Country" in front.


      const itemTemplate = (item: Country) => {
         return <div>Country {item.name}</div>;
      };


     return (
     <div className="card flex justify-content-center">
      <AutoComplete
        field="name"
        value={selectedCountry}
        suggestions={filteredCountries}
        completeMethod={search}
        onChange={(e: AutoCompleteChangeEvent) => setSelectedCountry(e.value)}
        itemTemplate={itemTemplate}
        selectedItemTemplate={itemTemplate}
        panelFooterTemplate={panelFooterTemplate}
        dropdown={true}
      />
    </div>
  );

When user clicks on this drop down the'd see

enter image description here

When they select a country I want to use only the country name "Afghanistan" to the call back but I want display "Country Afghanistan" in the box.

enter image description here

In order to do that, I use the selectedItemTemplate and I pass in the same function to prepend the word "Country". However, when I do this, I only see the value [object Object].

enter image description here

How can I display exact what the user selected in the drop down?


Solution

  • so I'm unsure the PrimeReact document was not clear or it was me not getting it but it looks like I can set the selectedItemTemplate to call a function myUserConversionMethod directly.

    selectedItemTemplate expects a string, so I can't used the existing function which returns JSX.Element, I just need to build one that produce a string value.

    
          const myUserConversionMethod = (item: Country) => { 
            return "Country " + item.name;
          };
    
          return (
           <div className="card flex justify-content-center">
             <AutoComplete
              field="name"
              selectedItemTemplate={myUserConversionMethod}
              value={selectedCountry}
              suggestions={filteredCountries}
              completeMethod={search}
              onChange={(e: AutoCompleteChangeEvent) => 
              setSelectedCountry(e.value)}
              itemTemplate={itemTemplate}
              dropdown={true}/>
            </div>
          );