How to code a Generic Searchable List which you can use for almost any situation on React
Navayuvan Subramanian
Building NeverForget ?? & OneInbox ?? | Full Stack Developer ?????? (React | NodeJS | Flutter | React Native) | Proud Engineer ???? | Mentor
We developers thrive to achieve code reusability on any tech we use. It not only reduces the lines of code but also enables us to make a single point of change.
While working on a project, we have situations to implement searchable lists in many places, but the problem we have is, that searchable lists have different list item layouts and search logic. So we should have implemented a dedicated component for a different searchable list and used it.
But this article will show you how to use a single generic searchable list component on all use cases not depending on its data type or list item layout.
Let's see the usage of the component.
Note: You can find the link for the code sandbox at the bottom of this article.
How should it be consumed?
If we are going to have a generic searchable list, we need to have the below things as input from the user (one who consumes the component), which means, we have to give the user the power to decide what component needs to be rendered as a list item, and what logic needs to be used when searching the item.
First, let's see how the component looks like
As we discussed, this component has
By now, you can see that we have given the required inputs to the component which are sufficient to implement a searchable list.
Now let's see the implementation part!
领英推荐
How has it been implemented?
You can understand what we did in this code. But let me explain in detail,
The list item is being mapped and we have called the `renderComponent` method from props to get the list item component mapped with the current item.
Then if the user does a search, we call the `searchLogic` method from props by passing the items and the searchText to get the filtered items and we set the returned value to the state to update the UI.
This is a very simple component but powerful. Because you can add any logics or UI changes in this component which will reflect on all the occurrences. You don't need to go and change every occurrence.
Hence, the component list item render logic and search logic are completely handled by the user which provides more power and flexibility to do whatever he/she wants to do.
And, the user can implement a searchable list with any type of data and search logic by using this.
This not only applies to searchable list, you can use this pattern to achieve any use case which needs the user control to render and handle the logics.
You can refer to the code sandbox below for executable code.
Follow Navayuvan Subramanian ?? for more content on tech! Also, feel free to ping me to have a curious tech chat (with a cup of coffee, if possible ??)