5

I'm using Material UI Auto complete to get list of countries, and I need to get the selected country id to send back to database.

<Autocomplete
   options={this.state.countries.map(option => option.name_en + ` (${option.name_native})`)}
   id="discountType"
   value={this.state.makeCountry}
   onChange={(e, value) => this.logCountry(e, value)}
   renderInput={(params) =>
   <TextField
      {...params}
      variant="outlined"
      label="Select make country"
   />}
/>

I need to send option.id to logCountry function alongside the value.

1 Answer 1

13

When creating your options, you can turn them into objects in a format such as:

const options = this.state.countries.map(option => ({ id: option.id, label: option.name_en + ` (${option.name_native})`}));

An then you can access the selected option id using onChange={(e, value) => this.logCountry(e, value.id)}.

I've forked the MUI Autocomplete's docs stackblitz example to implement such behavior, you can check it here.

Sign up to request clarification or add additional context in comments.

1 Comment

It worked. I just had to use getOptionLabel instead of value. Thank you so much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.