How to set up a filter to render only specific objects from an array in react?

I have an array of objects that is filled from a json file.

import ContentList from “../lists/contentList.json”;
Contentlist

In my App, I want to be able to select a category and show only the objects of that category.
Green selected

My approach was this:
I have a copy of my ContentList, the RenderList, which is the list that gets rendered.

Each time a filter-button is pressed in the app, the function handleSelectCategory gets triggered, which should update the RenderList.

import ContentList from "../lists/contentList.json";
import { useState } from "react";

function Body() {
  const [selectedCategory, setSelectedCategory] = useState("all");
  const [RenderList, setRenderList] = useState(
    ContentList.map((e) => ({ ...e }))
  );

  const handleSelectCategory = (category: string) => {
    setSelectedCategory(category);
    resetRenderList();
    updateRenderList(category);
  };

  const resetRenderList = () => {
    setRenderList(ContentList.map((e) => ({ ...e })));
  };

  const updateRenderList = (selectedCategory: string) => {
  setRenderList(
    RenderList.filter((cont) => cont.category == selectedCategory)
    );
  };

Right now the filter works the first time I press a button, but when I then press a different button, the list is empty. So the RenderList seems to not be resetted to the original ContentList. I just started learning React and couldn’t find an answer to that specific problem.

You should filter the original list not the already filtered list (;

import ContentList from "../lists/contentList.json";
import { useState } from "react";

function Body() {
  const [selectedCategory, setSelectedCategory] = useState("all");
  const [RenderList, setRenderList] = useState(
    ContentList.map((e) => ({ ...e }))
  );

  const handleSelectCategory = (category: string) => {
    setSelectedCategory(category);
    resetRenderList();
    updateRenderList(category);
  };

  const resetRenderList = () => {
    setRenderList(ContentList.map((e) => ({ ...e })));
  };

  const updateRenderList = (selectedCategory: string) => {
  setRenderList(
    ContentList.filter((cont) => cont.category == selectedCategory)
    //^HERE^
    );
  };

if you wondering why the resetRenderList doesn’t do the same thing then remember Calling the set function does not change state in the running code, which implies that you can’t call setState sequentially and expect it to work. It will update the state on the next render so you shouldn’t call it multiple times.

1

It may help if you review your code based on what is a state and what should not be a state ?

As you know, the React system reacts to the changes in state, and thus it makes the UI interactive.

Let us discuss the interactions in your app.

The first interaction is when the user clicks on the button and makes a selection. And the corresponding reaction expected in the UI is that the list should filter and display accordingly. Therefore which is the absolute minimal representation of state to keep in the app? It is the only one state with respect to the selection. Once this piece of state is made available in the app, a lot of information can be computed based on it. For example, a filtered list can be computed based on the state changes in selection. This approach is in line with the principle DRYDo not repeat yourself. This has been discussed based on the documentation here.

Now coming to the code, selectedCategory is the minimal required state. The RenderList can always be computed. This will reduce the code in the app as well. Please see below a sample code done based on these lines. Please see if it is useful. You can also see the test results enclosed below.

App.js

const { useState } = require('react');

export default function App() {
  const [selection, setSelection] = useState('all');
  return (
    <>
      <ul>
        {list
          .filter((item) =>
            selection == 'all' ? true : item.category === selection
          )
          .map((item) => (
            <li key={item.name}>{item.name + ',' + item.category}</li>
          ))}
      </ul>
      <button onClick={() => setSelection('red')}>Red</button>
      <button onClick={() => setSelection('green')}>Green</button>
      <button onClick={() => setSelection('yellow')}>Yellow</button>
      <button onClick={() => setSelection('blue')}>Blue</button>
      <button onClick={() => setSelection('all')}>All</button>
    </>
  );
}

const list = [
  {
    name: 'a',
    category: 'red',
  },
  {
    name: 'b',
    category: 'green',
  },
  {
    name: 'c',
    category: 'green',
  },
  {
    name: 'd',
    category: 'blue',
  },
  {
    name: 'e',
    category: 'yellow',
  },
  {
    name: 'f',
    category: 'red',
  },
  {
    name: 'g',
    category: 'green',
  },
];

npm list

[email protected]
├── [email protected]
├── [email protected]
└── [email protected]

Test run results:

  1. All – on load of the form
  1. On selecting green

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật