So I am trying to make a dynamic dropdown where user can add values to the dropdown list. The user should be able to see the new value in the dropdown list. I am using CreatableSelect from react-select library for this. Here is my code for the Custom Dropdown:
import React, {useState} from "react";
import CreatableSelect from "react-select/creatable";
const CustomDropdown = props => {
const {options}=props;
// const {optionList}=component;
const [types, setTypes] = useState(options);
const [inputValue, setInputValue] = useState("");
// const [typeValue, setTypeValue] = useState("");
const handleChange = (field, value) => {
switch(field) {
case "types":
setTypes(value);
break;
default:
break;
}
};
// const getSelectedValue = () => types.filter(item =>
// types.has(item.value));
const createOption=label=>({label, value:label});
const handleKeyDown=event=>{
switch (event.key){
case "Enter":
setTypes([
...types,
createOption(inputValue)
]);
break;
default:
break;
}
};
const handleInputChange = value => {
setInputValue(value);
console.log(value);
};
return (
<CreatableSelect
onChange={value => handleChange("types", value)}
options={types}
// value={getSelectedValue()}
inputValue={inputValue}
placeholder="Type something and press Enter"
onKeyDown={handleKeyDown}
onInputChange={handleInputChange}
/>
);
};
export default CustomDropdown;
Here is my App.js file:
import CustomDropdown from "./CustomDropdown";
export default function App() {
const optionList = [
{ label: "Core", value: "Core" },
{ label: "CPU", value: "CPU" },
{ label: "Databases", value: "Databases" },
{ label: "Device", value: "Device" },
{ label: "User", value: "User" }
];
return <CustomDropdown options={optionList} />;
}
The problem I am facing right now is after pressing enter button, I only see the newly added text. The dropdown doesn't open again at all. I want the dropdown to open with the newly added value at the last in it. Anyone who can rectify my mistake?