Skip to content

Instantly share code, notes, and snippets.

@arakawa-s
Last active November 30, 2020 02:04
Show Gist options
  • Save arakawa-s/55d8162d156b11cc0c52b5ec193e2e9f to your computer and use it in GitHub Desktop.
Save arakawa-s/55d8162d156b11cc0c52b5ec193e2e9f to your computer and use it in GitHub Desktop.
Advent Calendar 2020 example4
export const SearchHeaderSuggest = forwardRef<HTMLDivElement, Props>(
({ items, onSelect, onBlurSuggest, onClearAll }, ref) => {
const onBlur = useCallback<FocusEventHandler<HTMLDivElement>>(
(e) => {
// サジェスト内の各項目はblurイベントを発生させず、全体を抜けた時に1回呼ぶ
if (
// ① ノード内でフォーカスが遷移したか判定
(ref as MutableRefObject<HTMLDivElement>).current?.contains(
e.relatedTarget as Node
)
) {
e.preventDefault();
e.stopPropagation();
} else {
// ② 引数のblur処理を実行
onBlurSuggest(e);
}
},
[ref, onBlurSuggest]
);
return (
<div tabIndex={0} ref={ref} onBlur={onBlur}>
<div>
<ul>
{items.map((item) => (
<SuggestItem key={item.name} item={item} onSelect={onSelect} />
))}
</ul>
<button onClick={onClick}>全てクリア</button>
</div>
</div>
);
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment