If you're considering between using material-ui
directly or EditableDropdown
, I would recommend opting for material-ui
as it offers more flexibility and fewer limitations.
Furthermore, utilizing a newer version of Material-UI is advisable for improved features and performance.
Below is a code snippet in Material-UI (V4.9.5) that achieves the desired functionality. You can apply CSS for styling if needed:
import React from 'react';
import TextField from '@material-ui/core/TextField';
import Autocomplete, { createFilterOptions } from '@material-ui/lab/Autocomplete';
const filter = createFilterOptions();
export default function FreeSoloCreateOption() {
const [value, setValue] = React.useState(null);
return (
<Autocomplete
value={value}
onChange={(event, newValue) => {
if (newValue && newValue.inputValue) {
setValue({
title: newValue.inputValue,
});
return;
}
setValue(newValue);
}}
filterOptions={(options, params) => {
const filtered = filter(options, params);
if (params.inputValue !== '') {
filtered.push({
inputValue: params.inputValue,
title: `Add "${params.inputValue}"`,
});
}
return filtered;
}}
id="free-solo-with-text-demo"
options={top100Films}
getOptionLabel={option => {
// e.g value selected with enter, right from the input
if (typeof option === 'string') {
return option;
}
if (option.inputValue) {
return option.inputValue;
}
return option.title;
}}
renderOption={option => option.title}
style={{ width: 300 }}
freeSolo
renderInput={params => (
<TextField {...params} label="Free solo with text demo" variant="outlined" />
)}
/>
);
}
// Top 100 films as rated by IMDb users. http://www.imdb.com/chart/top
const top100Films = [
{ title: 'Raiders of the Lost Ark', year: 1981 },
{ title: 'Rear Window', year: 1954 },
{ title: 'The Pianist', year: 2002 },
{ title: 'The Departed', year: 2006 },
{ title: 'Terminator 2: Judgment Day', year: 1991 },
{ title: 'Back to the Future', year: 1985 },
{ title: 'Whiplash', year: 2014 },
{ title: 'Gladiator', year: 2000 },
{ title: 'Memento', year: 2000 },
{ title: 'The Prestige', year: 2006 },
{ title: 'The Lion King', year: 1994 },
{ title: 'Apocalypse Now', year: 1979 },
{ title: 'Alien', year: 1979 },
{ title: 'Sunset Boulevard', year: 1950 },
{
title: 'Dr. Strangelove or: How I Learned to Stop Worrying and Love the Bomb',
year: 1964,
},
];
For more information, visit: https://material-ui.com/components/autocomplete/
You can access the code here: https://codesandbox.io/s/gbljf
Please let me know if this solution serves your needs.