Home > Software engineering >  I have created a checkbox filter in react but i want all the options to be visible before i start fi
I have created a checkbox filter in react but i want all the options to be visible before i start fi

Time:07-16

The problem with the code below is that the items start showing up when i click then in the filter, what i want to do is have all the items available and then when i start filtering have only the ones show that are filtered. Should i solve this in the function or in the component with some conditional?


// Data 

const data = [
  {
    id: 0,
    poging: "Stoep",
  },
  {
    id: 1,
    poging: "Bon",
  },
  {
    id: 2,
    poging: "Bal",
  },
];

// Filter function

function Filters() {
  const [items, setItems] = useState(data);
  const [filters, setFilters] = useState([]);

  const clickFunction = (e) => {
    const listItem = e.target.parentNode;
    const list = listItem.parentNode;

    // Loop through filter items
    const filterList = Array.from(list.querySelectorAll("li"));

    // Create new array based on the checked filters and change filter state
    const newArray = filterList
      .filter((item) => item.querySelector("input:checked"))
      .map((item) => item.querySelector("label").textContent.toLowerCase());

    setFilters(newArray);
  };

 // Filter list
 <ul onChange={(e) => clickFunction(e)}>
   <li>
     <label htmlFor="stoep">Stoep</label>
     <input type="checkbox" name="" id="stoep" />
   </li>
   <li>
     <label htmlFor="bon">Bon</label>
     <input type="checkbox" name="" id="bon" />
   </li>
   <li>
     <label htmlFor="bal">Bal</label>
     <input type="checkbox" name="" id="bal" />
   </li>
 </ul>

// Output of the items
 <ul>
   {items
      .filter((item) => filters.includes(item.poging.toLowerCase()))
      .map((item) => {
                return (
                  <li key={item.id}>
                    <div>{item.poging}</div>
                  </li>
                );
              })}
          </ul>

CodePudding user response:

that seems pretty easy - just change this:

.filter((item) => filters.length === 0 || filters.includes(item.poging.toLowerCase()))
  • Related