Material UI Autocomplete component (React) - I am working on Autocomplete component that will not show any option values by default until you type in a value in React. All the examples I saw in https://mui.com/material-ui/react-autocomplete/ display options values on key focus. Does anyone know how I can achieve this? I only want the matching option values to show when user start typing the value my code below:
import { Autocomplete, TextField } from '@mui/material';
const TestAutoComplete = () => {
const top100Films = [
{ title: 'The Shawshank Redemption', year: 1994 },
{ title: 'The Godfather', year: 1972 },
{ title: 'The Godfather: Part II', year: 1974 },
{ title: 'The Dark Knight', year: 2008 },
{ title: '12 Angry Men', year: 1957 },
{ title: "Schindler's List", year: 1993 },
{ title: 'Pulp Fiction', year: 1994 }
]
const flatProps = {
options: top100Films.map((option) => option.title),
};
return (
<Autocomplete
{...flatProps}
id="flat-demo"
renderInput={(params) => (
<TextField {...params} label="Movie" />
)}
/>
)
};
export default TestAutoComplete;
CodePudding user response:
You could add a condition to render the options only after typing some value, something like this:
import React, { useState } from 'react';
import { Autocomplete, TextField } from '@mui/material';
const TestAutoComplete = () => {
const [value, setValue] = useState('');
const top100Films = [
{ title: 'The Shawshank Redemption', year: 1994 },
{ title: 'The Godfather', year: 1972 },
{ title: 'The Godfather: Part II', year: 1974 },
{ title: 'The Dark Knight', year: 2008 },
{ title: '12 Angry Men', year: 1957 },
{ title: "Schindler's List", year: 1993 },
{ title: 'Pulp Fiction', year: 1994 }
]
return (
<Autocomplete
inputValue={value}
onInputChange={(event, newValue) => setValue(newValue)}
options={
value.length > 0
? top100Films.map(option => option.title)
: []
}
id="flat-demo"
renderInput={params => <TextField {...params} label="Movie" />}
/>
)
};
export default TestAutoComplete;