@material-ui/lab#AutocompleteCloseReason TypeScript Examples

The following examples show how to use @material-ui/lab#AutocompleteCloseReason. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SearchBox.tsx    From log4brains with Apache License 2.0 4 votes vote down vote up
export function SearchBox(props: SearchBoxProps) {
  const classes = useStyles();

  const {
    onOpen,
    onClose,
    open: openProp,
    onQueryChange,
    query,
    results,
    loading = false,
    ...otherProps
  } = props;

  const [open, setOpenState] = useControlled({
    controlled: openProp,
    default: false,
    name: "SearchBox",
    state: "open"
  });

  const handleOpen = (event: React.ChangeEvent<{}>) => {
    if (open) {
      return;
    }
    setOpenState(true);
    if (onOpen) {
      onOpen(event);
    }
  };

  const router = useRouter();

  const handleClose = (
    event: React.ChangeEvent<{}>,
    reason: AutocompleteCloseReason
  ) => {
    if (!open) {
      return;
    }
    setOpenState(false);
    if (onClose) {
      onClose(event, reason);
    }
  };

  let noOptionsText: React.ReactNode = "Type to start searching";
  if (loading) {
    noOptionsText = (
      <div style={{ textAlign: "center" }}>
        <CircularProgress size={20} />
      </div>
    );
  } else if (query) {
    noOptionsText = "No matching documents";
  }

  return (
    <Autocomplete
      {...otherProps}
      classes={{ paper: classes.acPaper }}
      options={results ?? []}
      getOptionLabel={(result) => result.title}
      renderInput={(params) => (
        <SearchBar
          {...params}
          open={open}
          onClear={(event) =>
            onQueryChange && onQueryChange(event, "", "clear")
          }
          className={classes.searchBar}
        />
      )}
      inputValue={query}
      onInputChange={(event, value, reason) => {
        // We don't want to replace the inputValue by the selected value
        if (reason !== "reset" && onQueryChange) {
          onQueryChange(event, value, reason);
        }
      }}
      open={open}
      onOpen={handleOpen}
      onClose={handleClose}
      filterOptions={(r) => r} // We hijack Autocomplete's behavior to display search results as options
      renderOption={(result) => (
        <>
          <SvgIcon fontSize="small">
            <AdrIcon />
          </SvgIcon>
          <Typography className={classes.resultTitle}>
            {result.title}
          </Typography>
        </>
      )}
      noOptionsText={noOptionsText}
      onChange={async (_, result) => {
        if (result) {
          await router.push(result.href);
        }
      }}
    />
  );
}