How to show Material-UI Autocomplete
drop-down list only when typing something? I added a Material-UI Autocomplete
component to one of my project. But the problem is when I clicked the TextField
, it automatically drop down all the list options. I want to drop down only suggestions when the user is going to type something. Below is my code.
import React, { useEffect, useState } from "react";
import { Grid, Popper } from "@material-ui/core";
import axios from "axios";
import Autocomplete from "@material-ui/lab/Autocomplete";
import { useStyles, CssTextField } from "./classes";
export default function SearchItems({ setFieldValue, dialogOpen }) {
const classes = useStyles();
const [results, setResults] = useState([]);
useEffect(() => {
loadSearchItemsList();
}, []);
//load restaurants and tags
const loadSearchItemsList = async () => {
try {
let { data } = await axios.get("/search");
// console.log(data)
setResults(data);
} catch (error) {
// setAlert({
// showAlert: true,
// severity: "error",
// message: "Loading failed!",
// });
dialogOpen(true)
}
};
return (
<Grid item xs={12} sm={12} md={12} lg={12} className={classes.gapSpace}>
<Autocomplete
id="free-solo-demo"
freeSolo
getOptionLabel={(option) => option.name}
autoComplete
onChange={(event, newValue) => {
if (newValue) {
const { id, type, name } = newValue;
setFieldValue("id", id);
setFieldValue("type", type);
setFieldValue("name", name);
} else {
setFieldValue("id", null);
setFieldValue("type", null);
setFieldValue("name", null);
}
}}
options={results}
renderInput={(params) => (
<CssTextField
{...params}
className={classes.input}
placeholder="Restaurant, Food"
variant="outlined"
id="custom-css-outlined-input"
/>
)}
/>
</Grid>
);
}
You can control the open
and inputValue
state of Autocomplete
and call setOpen(false)
to close the menu list when there is nothing in the inputValue
:
const [open, setOpen] = useState(false);
const [inputValue, setInputValue] = useState("");
return (
<Autocomplete
open={open}
onOpen={() => {
// only open when in focus and inputValue is not empty
if (inputValue) {
setOpen(true);
}
}}
onClose={() => setOpen(false)}
inputValue={inputValue}
onInputChange={(e, value, reason) => {
setInputValue(value);
// only open when inputValue is not empty after the user typed something
if (!value) {
setOpen(false);
}
}}
options={top100Films}
renderInput={(params) => (
<TextField {...params} label="Combo box" variant="outlined" />
)}
/>
);