Home > other >  How can I get the value of the Autocomplete Select of material-ui?
How can I get the value of the Autocomplete Select of material-ui?

Time:11-20

How can I get the value of what was selected in the drop down? I have these codes below but it will show this in the console.log:

MUI: The getOptionLabel method of Autocomplete returned number (0) instead of a string for 0.

import React, { useState } from "react";
import TextField from "@mui/material/TextField";
import Autocomplete from "@mui/material/Autocomplete";

export default function ComboBox() {
  const [selected, setSelected] = useState(0);
  const handleChange = (e) => setSelected(e.target.value);
  console.log(selected);

  return (
    <Autocomplete
      disablePortal
      id="combo-box-demo"
      options={Items}
      sx={{ width: 300 }}
      value={selected}
      onChange={handleChange}
      renderInput={(params) => <TextField {...params} label="Items" />}
    />
  );
}


const Items = [
  { label: "Car" },
  { label: "Book" },
  { label: "Chair" },
  { label: "Pencil" }
];

Also, will this work in material-ui ^4.12.3? codesandbox link: https://codesandbox.io/s/combobox-material-demo-forked-g88fi

CodePudding user response:

you need to get the second parameter of handleChange. and it is value.

 const handleChange = (e,v) => setSelected(v);

like this:

import React, { useState } from "react";
import TextField from "@mui/material/TextField";
import Autocomplete from "@mui/material/Autocomplete";

export default function Edit() {
    const [selected, setSelected] = useState( { label: "" });
    const handleChange = (e,v) => setSelected(v);
    console.log(selected);

    return (
        <Autocomplete
            disablePortal
            id="combo-box-demo"
            options={Items}
            sx={{ width: 300 }}
            value={selected}
            onChange={handleChange}
            renderInput={(params) => <TextField {...params} label="Items" />}
        />
    );
}


const Items = [
    { label: "Car" },
    { label: "Book" },
    { label: "Chair" },
    { label: "Pencil" }
];

it works very well for me.

  • Related