Skip to content Skip to sidebar Skip to footer

Material Ui Autocomplete: Can Tags Be Created On Events Aside From 'enter' Events?

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 cre

Solution 1:

Below is the approach I would recommend.

There are two main aspects to the approach:

  1. Use a "controlled" input approach for the Autocomplete so that you have full control over the current value.

  2. Specify the onKeyDown handler for the TextField input via params.inputProps.onKeyDown with appropriate logic for adding the new value.

import React from"react";
import TextField from"@material-ui/core/TextField";
import Autocomplete from"@material-ui/lab/Autocomplete";

export default function Tags() {
  const [value, setValue] = React.useState([top100Films[13]]);
  const handleKeyDown = event => {
    switch (event.key) {
      case",":
      case" ": {
        event.preventDefault();
        event.stopPropagation();
        if (event.target.value.length > 0) {
          setValue([...value, event.target.value]);
        }
        break;
      }
      default:
    }
  };
  return (
    <div style={{ width: 500 }}>
      <Autocomplete
        multiple
        freeSolo
        id="tags-outlined"
        options={top100Films}
        getOptionLabel={option => option.title || option}
        value={value}
        onChange={(event, newValue) => setValue(newValue)}
        filterSelectedOptions
        renderInput={params => {
          params.inputProps.onKeyDown = handleKeyDown;
          return (
            <TextField
              {...params}
              variant="outlined"
              label="filterSelectedOptions"
              placeholder="Favorites"
              margin="normal"
              fullWidth
            />
          );
        }}
      />
    </div>
  );
}

// Top 100 films as rated by IMDb users. http://www.imdb.com/chart/topconst top100Films = [
  { title: "The Shawshank Redemption", year: 1994 },
  { title: "The Godfather", year: 1972 },
// ... many more options
];

Edit Autocomplete keydown override

Here's a Typescript version:

/* eslint-disable no-use-before-define */
import React from"react";
import TextField from"@material-ui/core/TextField";
import Autocomplete, { RenderInputParams } from"@material-ui/lab/Autocomplete";

interfaceObjectOption {
  title: string;
  year: number;
}
type Option = ObjectOption | string;

interfaceMyInputProps {
  onKeyDown: (event: object) => void;
}
interfaceMyParamsextendsRenderInputParams {
  inputProps: MyInputProps;
}

export default function Tags() {
  const [value, setValue] = React.useState([top100Films[13]]);
  const handleKeyDown = event => {
    switch (event.key) {
      case",":
      case" ": {
        event.preventDefault();
        event.stopPropagation();
        if (event.target.value.length > 0) {
          setValue([...value, event.target.value]);
        }
        break;
      }
      default:
    }
  };
  return (
    <div style={{ width: 500 }}>
      <Autocomplete
        multiple
        freeSolo
        id="tags-outlined"
        options={top100Films}
        getOptionLabel={option => {
          if (typeof option === "string") {
            return option;
          }
          return option.title;
        }}
        value={value}
        onChange={(event, newValue) => setValue(newValue)}
        filterSelectedOptions
        renderInput={(params: MyParams) => {
          params.inputProps.onKeyDown = handleKeyDown;
          return (
            <TextField
              {...params}
              variant="outlined"
              label="filterSelectedOptions"
              placeholder="Favorites"
              margin="normal"
              fullWidth
            />
          );
        }}
      />
    </div>
  );
}

// Top 100 films as rated by IMDb users. http://www.imdb.com/chart/topconst top100Films: ObjectOption[] = [
  { title: "The Shawshank Redemption", year: 1994 },
  { title: "The Godfather", year: 1972 },
// ... many more options
];

Edit Typescript Autocomplete override keydown

Solution 2:

As answered here, just use the autoHighlight flag:

<AutocompleteautoHighlight {...} />

It will highlight the first option by default, so pressing enter will select it.

Post a Comment for "Material Ui Autocomplete: Can Tags Be Created On Events Aside From 'enter' Events?"