Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Material UI Autocomplete implementation with options containing array of objects (ID and label)

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!

like image 502
bonnopc Avatar asked Dec 15 '19 13:12

bonnopc


1 Answers

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.

like image 145
naeramarth7 Avatar answered Oct 29 '22 15:10

naeramarth7