Hello. I am working on a personal project using React.
I have three checkboxes that are supposed to filter the information in the table automatically when checked off (for example, if you check off "airline1", then only airline1 and its data will populate in the table). I would like some advice on how to do that using "Use State" and "Use Effect" because I believe using "Use States" and "Use Effect" would be the most efficient way to do this please. Here is the code that I have so far (see below):
import React, { useState } from "react";
import Table from "./components/Table/table";
import "./styles.css";
const list = [
{ id: "1", airline: "airline1", stops: 2, cost: 200 },
{ id: "2", airline: "airline2", stops: 2, cost: 100 },
{ id: "3", airline: "airline2", stops: 3, cost: 350 },
{ id: "4", airline: "airline3", stops: 1, cost: 90 },
{ id: "5", airline: "airline3", stops: 3, cost: 300 },
{ id: "6", airline: "airline1", stops: 1, cost: 100 }
];
const colNames = ["Id", "Airline", "Stops", "Cost"];
const App = (props) => {
const [filteredList, setFilteredList] = useState(list);
function filterData(list, filters) {
return list.filter((item) => filters.includes(item.airline));
}
console.log(filterData(list, "airline2")); // test
function changeSearch(e) {
if (e.target.checked) {
console.log("THIS IS TRUE");
if (e.currentTarget.value === "airline1") {
console.log("You have chosen airline1");
console.log(filterData(list, "airline1"));
//console.log(filterData(list, e.currentTarget.value));
return <p>test</p>;
} else if (e.currentTarget.value === "airline2") {
console.log("You have chosen airline2");
console.log(filterData(list, "airline2"));
} else if (e.currentTarget.value === "airline3") {
console.log("You have chosen airline3");
console.log(filterData(list, "airline3"));
}
} else {
console.log("THIS IS FALSE");
console.log(filterData(list, ["airline1", "airline2", "airline3"]));
}
}
return (
<div className="grid-container">
<div className="tableClass">
<Table list={list} colNames={colNames} />
</div>
<div className="filterClass">
<input
type="checkbox"
id="airline1"
value="airline1"
onChange={changeSearch}
/>{" "}
airline1
<br />
<input
type="checkbox"
id="airline2"
value="airline2"
onChange={changeSearch}
/>{" "}
airline2
<br />
<input
type="checkbox"
id="airline3"
value="airline3"
onChange={changeSearch}
/>{" "}
airline3
<br />
</div>
</div>
);
};
export default App;