How to filter in React?
Filtering can be pretty tough as a beginner to React. It took me days and a lot of practice to wrap my head around it. I know this blog will be helpful to anyone that is on the same struggle boat as I was. I am going to give you a walkthrough from one of my favorite labs I did to practice filtering.
The component above shows a code snippet of the filter dropdown which has an onChange event that takes in a callback function with the parameter of event.target.value to send back to the parent where the filterStocks function is defined. We are also passing the value attribute to props.filterTerm from the parent components state, this makes it a controlled form. Please note that filterStocks function and filterTerm state was sent down as a prop from the parent (MainContainer.js) (See below)
filterStocks function is setting the state to the value attribute of each dropdown option. In this case, it will depend on which option the user picks. If a user clicks “All” set the state to all, if a user clicks “Tech” they will set the state to “Tech” etc…
The next step will be to decide how we will be rendering the stocks and this will come down to conditional rendering. In the parent component, I defined a function that will decide on which stocks to render to the page based on the filters state change. (See below)
The whichStocksToRender function will be used to map through each of the stocks based on which condition is true and return <Stock/> components for each. My original array of stocks is stored in the state as stocks. So if a user filters by “All” it will return the original array and if the user picks any other option, it will filter the original array by the type of stock the user chooses.