Filter use in React

mern_practical

MERN Practical Explanation

Posted on February 7, 2024

Filter use in React
  const data = [2, 3, 5, 4, 6, 1, 7, 8, 9];

  const filteredData = data.filter((item) => {
    if (!selectedCategory) {
      // If no category is selected, include all items
      return true;
    } else if (selectedCategory === "Salon" && (item === 5 || item === 7 || item === 8 || item === 9)) {
      return true;
    } else if (selectedCategory === "Contructor" && (item === 1 )) {
      return true;
    } else if (selectedCategory === "Doctor" && (item === 2 || item === 4)) {
      return true;
    } else if (selectedCategory === "Teacher" && (item === 3 || item === 6)) {
      return true;
    }
    return false;
  });

Enter fullscreen mode Exit fullscreen mode
  const handleToggle = (event, item) => {
    event.preventDefault();
    if (expandedItems.includes(item)) {
      setExpandedItems(
        expandedItems.filter((expandedItem) => expandedItem !== item)
      );
    } else {
      setExpandedItems([item]);
    }
  };
Enter fullscreen mode Exit fullscreen mode
const handleEditUser = (id) => {
    if (usersData?.length > 0) {
      const editUserData = usersData.filter((val) => val?.id == id);
      setUserId(id);
      setUserCreateData({
        name: editUserData[0]?.name,
        email: editUserData[0]?.email,
        // password: "",
        roleId: editUserData[0]?.role_id,
      });
    } else {
      alert("users not available");
    }

Enter fullscreen mode Exit fullscreen mode

 const searchByRoleId = () => {
    setUsersData(usersDataApi);
    if (searchOption != "-1" && searchInput == "") {
      const newUsersData = usersDataApi.filter(
        (item) => item?.role_id == searchOption
      );
      setUsersData(newUsersData);
      // item?.role_name.toLowerCase().includes(searchInput?.toLowerCase())
    } else if (searchInput != "" && searchOption == "-1") {
      const newUsersData = usersDataApi.filter((item) =>
        item?.name.toLowerCase().includes(searchInput?.toLowerCase())
      );
      setUsersData(newUsersData);
    } else if (searchInput != "" && searchOption != "1") {
      const newUsersData = usersDataApi.filter(
        (item) => item?.role_id == searchOption
      );
      const newUsersData2 = newUsersData.filter((item) =>
        item?.name.toLowerCase().includes(searchInput?.toLowerCase())
      );
      setUsersData(newUsersData2);
    } else {
      setUsersData(usersDataApi);
    }
  };

Enter fullscreen mode Exit fullscreen mode
πŸ’– πŸ’ͺ πŸ™… 🚩
mern_practical
MERN Practical Explanation

Posted on February 7, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related