Open MartinJohannesNilsen opened 3 years ago
I have tried following these suggestions, but can't seem to get it working. I am using Typescript and Hooks
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;
In which I thought was going to work, but it did not. I even increased the timer to a second instead of 100ms.
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; }'.
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;
}
@leMaik Could you take a look at the PR? This issue can be closed
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?