diff --git a/src/components/Search.tsx b/src/components/Search.tsx index 47d738c4..781fbd34 100644 --- a/src/components/Search.tsx +++ b/src/components/Search.tsx @@ -21,6 +21,7 @@ class Search extends React.PureComponent { }; render() { + console.log(document.activeElement) const { type, onChange, diff --git a/src/components/TypeAhead.tsx b/src/components/TypeAhead.tsx index 4f28eded..a3b6c968 100644 --- a/src/components/TypeAhead.tsx +++ b/src/components/TypeAhead.tsx @@ -8,12 +8,16 @@ import OutsideClick from "./OutsideClick"; import OptionGroupRadio from "./OptionGroupRadio"; class TypeAhead extends React.PureComponent { + typeaheadInputRef: React.RefObject = React.createRef(); debouncedChange: () => void; static defaultProps: Partial = { debounceTime: 500, onClear: () => {}, - searchBox: ({ registerChange, onFocus, value }, props) => ( + searchBox: ( + { registerChange, onFocus, value, typeaheadInputRef, onBlur }, + props + ) => ( { registerChange(""); props.onClear(); } - } + }, + //@ts-ignore + ref: typeaheadInputRef, + onBlur }} value={value} errorMessage={props.errorMessage} @@ -45,7 +52,8 @@ class TypeAhead extends React.PureComponent { state: TypeaheadState = { value: this.props.initialValue || "", - showSuggestions: false + showSuggestions: false, + focussedElement: undefined }; onChange = () => { @@ -63,10 +71,15 @@ class TypeAhead extends React.PureComponent { private onFocus = () => { this.setState({ - showSuggestions: true + showSuggestions: true, + focussedElement: document.activeElement }); }; + private onBlur = () => { + this.setState({ focussedElement: document.activeElement }); + }; + private onSelect = _value => { this.props.onSelect(_value, this.props); @@ -79,7 +92,7 @@ class TypeAhead extends React.PureComponent { render() { const { className, searchBox, dropdownClassName, children } = this.props; - const { showSuggestions, value } = this.state; + const { showSuggestions, value, focussedElement } = this.state; return ( { { registerChange: this.registerChange, onFocus: this.onFocus, - value + onBlur: this.onBlur, + value, + typeaheadInputRef: this.typeaheadInputRef }, this.props )} - {showSuggestions && ( + {(focussedElement === this.typeaheadInputRef.current || + showSuggestions) && (
{children} diff --git a/src/components/typings/Typeahead.ts b/src/components/typings/Typeahead.ts index 059119e2..ba7bdf08 100644 --- a/src/components/typings/Typeahead.ts +++ b/src/components/typings/Typeahead.ts @@ -11,6 +11,8 @@ export interface TypeaheadProps { registerChange: (text: string) => void; onFocus: FocusEvent; value: string; + typeaheadInputRef: React.RefObject; + onBlur: FocusEvent; }, props: TypeaheadProps ) => JSX.Element; @@ -33,4 +35,5 @@ export interface TypeaheadProps { export interface TypeaheadState { value: string; showSuggestions: boolean; + focussedElement: React.ReactNode; }