TeamWertarbyte / material-ui-search-bar

Material design search bar
https://mui.wertarbyte.com/#material-ui-search-bar
MIT License
261 stars 82 forks source link

Can't seem to autofocus the searchbar #95

Open MartinJohannesNilsen opened 3 years ago

MartinJohannesNilsen commented 3 years ago

I am trying to automatically focus this component on render.

Have tried passing autoFocus as a prop, as the ReadMe states that "Any other properties supplied will be spread to the underlying Input component." Am I doing something wrong here?

MartinJohannesNilsen commented 3 years ago

15

I have tried following these suggestions, but can't seem to get it working. I am using Typescript and Hooks

MartinJohannesNilsen commented 3 years ago

Have tried using the following approach:

searchbar in view:

[...]
const [inputRef, setInputFocus] = useFocus();
useEffect(() => {
    setTimeout(() => {
    setInputFocus();
    }, 1000);
}, []);
[...]
<SearchBar
    {...inputRef}
    className={classes.searchBar}
    value={searchString}
    onChange={(newString: string) => setSearchString(newString)}
    onRequestSearch={handleSearch}
    searchIcon={<SearchIcon color="primary" />}
    closeIcon={<CloseIcon color="primary" />}
/>

useFocus.ts

import { MutableRefObject, useRef } from "react";
const useFocus = (): [any, () => void] => {
  const htmlElRef: MutableRefObject<any> = useRef(null);
  const setFocus = (): void => {
    htmlElRef?.current?.focus?.();
  };
  return [htmlElRef, setFocus];
};
export default useFocus;

source

In which I thought was going to work, but it did not. I even increased the timer to a second instead of 100ms.

MartinJohannesNilsen commented 3 years ago

I see that in this example, the autoFocus-prop is properly working. I've tested it, and it seems to work in jsx, but not in tsx.

Type '{ autoFocus: true; className: string; value: string; onChange: (newString: string) => void; onRequestSearch: () => void; placeholder: string; searchIcon: Element; closeIcon: Element; }' is not assignable to type 'IntrinsicAttributes & SearchBarProps & { children?: ReactNode; }'.
  Property 'autoFocus' does not exist on type 'IntrinsicAttributes & SearchBarProps & { children?: ReactNode; }'.
MartinJohannesNilsen commented 3 years ago

Fixed it locally by changing index.d.ts for now. You may have a better solution for this, but I just added autoFocus?: boolean to the interface SearchBarProps.

declare module 'material-ui-search-bar' {
  export interface SearchBarProps {
      [...]
      autoFocus?: boolean;
  }
  const SearchBar: React.ComponentType<SearchBarProps>;
  export default SearchBar;
}
MartinJohannesNilsen commented 3 years ago

@leMaik Could you take a look at the PR? This issue can be closed