DEV Community

Kevin Dutzy
Kevin Dutzy

Posted on

Create a dynamic route for search bar

Recently I created a project that allowed users to choose from multiple different options to search by (name, brand, type, size), and when creating routs in the backend - I thought there must be a cleaner more efficient way to do this rather than having a separate method for each search type. After thinking if over I realized that through params, I had the ability to pass in the value of both the search type as well as the value of the search, and use those within my method to create a dynamic search that would return the desired results. I'll go ahead and walk through the steps of setting someting like this up in both the front end and back end.

Start with the back end

to start, you'll want to create a 'get' route that will be targeting your desired controller where the method will live. something like this

get '/:option/:search', to:'synth_modules#search'

from there, you need to set up a method in your controller that will be looking to find a specific instance, based on the provided info from params. it might look something like this :

Image description

in the above image - I'm declaring a variable that will be assigned the instance that matches the search. if a instance is created, it will return that data as json back to the front end, and if not the error will be sent up. As you can see, im using a custom method .filtered_synths and passing in the params to that method, it makes things cleaner in my opinion to have a single method called rather than .where's and other methods flying around.

The Front End

now that the back end is set up to receive data from the front end, heres how we would set up our fetch request in a react front end.

first, have a form built out based on your own needs, mine had a drop-down where users can select which attribute they would like to search by, followed by a text box where the search value would go. Each of those values are set to state, so that I can reference that in my fetch URL, and it can stay updated on each change of the form. Once the submit button is clicked, it triggers a fetch request, that looks like this

Image description

as you can see you need to interpolate the state values of 'option' as well as 'search' inside the URL, and with the response, set that return object to the state that is rendering all of your cards, in my case is was all synth modules, so now the only objects that will be rendered are the modules that match the search value.

There are plenty of ways to execute this solution, but at the time this seemed like a efficient way to minimize code and multiple methods, by combining all searches into one method with the powerful use of params.

Top comments (0)