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?
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
If you just want to display name in Textfield, You could try this
getOptionLabel={option => option.id}
renderOption={option => <>{option.name}</>}
If you want to display name in TextField and OptionLabel but want to get id as value of TextField in order to store id after form submission. You could try this
getOptionLabel={(option) => option.name}
renderOption={(option) => (
<>
{option.name} ({option.surname})
</>
)}
onChange={(event, newValue) => {
setValue(newValue);
setCustomValue(newValue.id);
}}
using onChange event you could select any field of the option you want to get as value.In this example I stored id of the option in the state. Complete working example is here https://codesandbox.io/s/material-demo-forked-wlzr8?file=/demo.js:804-1084
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With