seanmturley / natureddit

A simple Reddit client, featuring a landing page dedicated to nature with posts pulled from a curated list of subreddits.
0 stars 1 forks source link

Add logic to toggle search dropdown visibility #127

Closed seanmturley closed 1 year ago

seanmturley commented 1 year ago

Description

The SearchDropdown should only be rendered when there are subreddit results returned from the API for the current search term, and when the input has focus.

seanmturley commented 1 year ago

Partly implemented as part of issue #128.

seanmturley commented 1 year ago

Done, but this was more complicated than anticipated.

I expected to be able to control the dropdown visibility entirely by setting a value in state with onFocus and onBlur on the <input>. This worked as expected when interacting with most of the page. However, there were two issues when interacting with the dropdown itself:

Keyboard interaction issue

Problem

Selecting dropdown options with the arrow keys and enter didn't trigger an onBlur event.

Solution

This was fixed by adding searchInput.current.blur() after the useNavigate calls in handleInputSubmit and the enterPress useEffect.

Mouse interaction issue

Problem

Selecting dropdown options with the mouse did trigger and onBlur event as expect, but prevented any onClick events from running (including following links). This is an execution order issue - onBlur is triggered by onMouseDown events, immediately shutting the dropdown. This means that when the onClick attempts to resolve (which requires onMouseDown + onMouseUp on the same element), the clicked element is no longer present on the page.

Solution

The solution was based on a Stack Overflow answer. In this case it was necessary to add a onMouseDown with event.preventDefault() to all clickable elements, and an onClick that included searchInput.current.blur().