Skip to content
Advertisement

REACT JS – Working on eshop-like project, got stuck with product filters

So hello. I’ve been working on my own stuff as I believe it is the best way to learn things. So I got stuck, I am quite new to this react thing. I got this code, as you can see I have few checkboxes there, and what I want to achieve is to check the box to filter (hide) products from the array. I kinda got to the point where I don’t know what should I do next, I know I need to put something into constructor, but I can’t really figure out what. Can you please help me with that? Thanks!

JavaScript
JavaScript
JavaScript

Advertisement

Answer

JavaScript

Okay, so.. First of all, you need to set initial state to be able to trigger re-renders in you components (this what @alexsc _’s answer was about).

Second of all, if you’re trying to filter on an array of objects, you must have a field that you can use for that (note that I added a type variable that would contain the type of cpu or gpu, etc.. for each product). The React way to render multiple elements with similar values are usually done with mapping the related array (notice the mapping of products that returns an input element).

Following this logic, the third modification I made on your code was the filtering of products. This might not make any sense whatsoever, but when you click on an input element, it will trigger a re-render, due to the modification of a state member. This is why you need to have initial state and this is why I put the line, this.state[product.type] in the filter. With this, React will detect a change in state and will attempt to re-render your component, which calls the filter method again with updated values.

To make it more clear, let’s say you filter by cpu. You’ll click on the input which says cpu. This will set the cpu state variable to true. React detects that the state has changed so it attempts a re-render. Then it’ll call the filter method on your products array again and this.state[product.type] will eventually be this.state['cpu'] which will evaluate to true.

NOTE: If you’re unfamiliar with any of the used syntax, you should checkout the docs

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement