Skip to content

Instantly share code, notes, and snippets.

@gonzalez-aj
Last active July 26, 2023 04:13
Show Gist options
  • Save gonzalez-aj/0743a562563613777625dd121edf81f2 to your computer and use it in GitHub Desktop.
Save gonzalez-aj/0743a562563613777625dd121edf81f2 to your computer and use it in GitHub Desktop.
SearchBar JavaScript Next.JS

Search bar with dynamic routing using Next.JS in React and Fetch

Today I learned how to create a search bar to search through my data and push the result to a dynamically routed page. I searched some ways to ways to build the search bar without using the hook useRouter()

Big shout out to @ryanmbigelow for his ticket and cueing me to look at @ericlfrey's ticket as well. Thank you for rubber ducking with me about dynamic routes, Eric!

This is the branch I have with the functioning search bar that searches my data by role and name property types. This is the searchBar component I first created to get a search bar on the DOM. The component lives exclusively on my team page.

The input field for the search bar has an onChange event handler. The handler updates the component's state with lowercase letters of the current input value in order to later on compare lower case letters to lower case letters. This way we are comparing the user's search query to the data in "an apples to apples" way.

When the user submits the search, and the search is not an empty string if (searchInput !== '') then the component uses the useRouter hook to navigate to the /search/${searchInput} route. searchInput is the state we are tracking and managing with the useState hook.

This then navigates to the Search component. Within this component I use the API call getMembers to get the array of all the members from Firebase, and then the .filter method to filter through if the name or role of each member includes the user's search query.

useState tracks and manages the state variable members. In the return, the component maps over this array of members with the MemberCard component.

@ryanmbigelow's experience with the documentation:

Thanks for posting this @AngieMGonzalez, I was able to get my search bar up and running thanks to your explanation!

My main error in all this was that I was trying to filter within my SearchBar() component and not within my SearchResults() page! All the search bar component needs to do is capture the input and route it to the dynamic [searchInput] page. Then on your search input page, you already have the input and THEN you can use your API call to filter based on what your search was.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment