autocompletematerial-ui

Material UI <Autocomplete /> different label than option value


I have a Material UI <Autocomplete /> component I am using where you can type in someone's name and it will provide a list of people to select from. This is a pretty standard use case, however I need the selected item in the form to be different than the label.

Currently if you pick the entry labelled "John Smith", the text field will be filled with "John Smith". Instead, I want to fill the text field with that user's ID.

The data for autocomplete is an array of objects like this:

{ "name": "John Smith", "id": 123456789 }

How can I make the autocomplete component put the user ID in the text field instead of the user label?


Solution

  • You can customize renderOption props in Material-UI Autocomplete

    Render the option, use getOptionLabel by default.
    Signature: function(option: T, state: object) => ReactNode
    option: The option to render.
    state: The state of the component.

    As for the code

    getOptionLabel={option => option.name}
    renderOption={(option) => <span>{option.name}</span>}
    

    Refer to the demo in an official document