I am currently working with the freesolo Autocomplete and my particular use case requires tags to be created when commas or spaces follow the input text. Autocomplete currently creates tags on the Enter event, but I don't think there is anything built into Autocomplete yet that supports tag creation on any other event. I'm wondering if I'm missing anything, or if I'm not, how could I approach this problem?
Currently, I'm attempting to use the onInputChange attribute in Autocomplete to capture the string coming in. I check that string for commas and spaces, and on a successful find of one of those characters I manually fire off the Enter event using some native JS code. This works in some cases, but not in all cases and accounting for all cases is becoming tedious. This approach seems like it's prone to a lot of issues, and I'm not convinced it's the best way to go about implementing tag creation on different events. Looking for some thoughts. Thanks
onInputChange
attribute usage:
<Autocomplete
multiple
freeSolo
filterSelectedOptions
id="auto-complete"
options={foo.map(bar => bar.name)}
ref={autoRef}
onInputChange={(e, value) => {
createTagOnEvent(value);
}}/>
Searching through input for commas and spaces and firing off Enter event manually:
const createTagOnEvent = (bar) => {
if (pattern.test(bar)) {
const ke = new KeyboardEvent("keydown", {bubbles: true, cancelable: true, keyCode: 13});
autoRef.current.dispatchEvent(ke);
}
};
Below is the approach I would recommend.
There are two main aspects to the approach:
Use a "controlled" input approach for the
Autocomplete
so that you have full control over the current value.Specify the
onKeyDown
handler for theTextField
input viaparams.inputProps.onKeyDown
with appropriate logic for adding the new value.Here's a Typescript version: