Revolutionizing Search Interface: A Context-Driven Approach
The Problem: Hidden Filters
At our company, we stumbled upon a surprising issue: most users weren’t utilizing filters when searching on our platform. A closer look at our analytics revealed that users simply didn’t know filters existed. To tackle this problem, we embarked on a mission to rebuild our UI, putting filters front and center.
The Challenges Ahead
Rebuilding our search interface came with its own set of hurdles. We faced three main concerns:
- Managing focus across multiple filter dropdown menus with nested inputs
- Ensuring only one menu was open at a time
- Triggering a new search when a filter was selected
The Solution: Context API and Refs
We overcame these challenges by leveraging React’s Context API and refs to create a centralized system for managing menu states and input focus.
Context API: Simplifying Data Injection
The Context API, introduced in React v16.3, helps avoid prop drilling, where data is manually passed down a component tree. By creating a Context.Provider, we can inject data into child components that need it. The useContext Hook allows components to subscribe to the closest Provider above them in the component tree.
Managing Menu States and Focus
In our case, Context enabled us to keep track of which menu should be open in our parent component and pass that value down to its children. The key lies in passing a setter function, allowing components consuming our context value to update the state in our parent component, triggering a re-render with the new menu visible. We can similarly manage the focus state of various inputs in the search bar and filter menus.
Refs: Direct Access to Elements
Refs provide a way to access elements (JSX or HTML) directly. While they can be an antipattern, our use case required us to use refs to directly access the three inputs in our component tree and utilize the browser’s.focus() method. We created three refs in our parent component, pointing to the search bar input, first filter menu input, and second filter menu input. By passing these refs down to child components, we can update focus states based on user interaction.
Combining Context and Refs for a Seamless Experience
By combining Context and refs, we created a more straightforward way of managing display and focus states within our new search interface. This approach allows for a more consistent user experience and easier code maintenance.