13

I am using Material UI Autocomplete for my project. As shown in official documentation, my options are,

let options = [
   { id: "507f191e810c19729de860ea", label: "London" },
   { id: "u07f1u1e810c19729de560ty", label: "Singapore" },
   { id: "lo7f19re510c19729de8r090", label: "Dhaka" },
]

Then, I am using Autocomplete as,

import React, { Component, Fragment, useState } from "react"
import TextField from '@material-ui/core/TextField';
import Autocomplete from '@material-ui/lab/Autocomplete';
import options from "/options"

function SelectLocation(props){
    const [ input, setInput ] = useState("");

    const getInput = (event,val) => {
        setInput(val);
    }

    return (
        <Autocomplete
            value={input}
            options={options}
            renderOption={option => <Fragment>{option.label}</Fragment>}}
            getOptionLabel={option => option.label}
            renderInput={params => {
                return (
                    <TextField 
                        {...params} 
                        label={props.label} 
                        variant="outlined" 
                        fullWidth
                    />
                )
            }}
            onInputChange={getInput}
        />
    )
}

Now my UI (options list) is showing what I expected. The problem is, I am getting London or Singapore as a value of my input, but I want to get the selected object or ID from this input.

I've followed their documentation thoroughly, but couldn't find a way!

2 Answers 2

6

onInputChange get's fired with the actual content of the input.

You might want to use the onChange event exposed by the input props, which will return the selected element. The id should then be available as val.id in your getInput callback.

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

Comments

-1

For others that might have the same issues as I. In case your option are array of objects (or any other data structure), use the following:

getOptionLabel new api of autoComplete will allow for you to select any option value from your data source.

Example

<SearchInput
  getOptionLabel={(option) => option["whateverKeyYouNeed"]}
  .
  .
  .
  .
/>

More here >>> https://mui.com/material-ui/react-autocomplete/

Comments

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.