Home > Net >  React: Filter table data with multiple column values
React: Filter table data with multiple column values

Time:09-09

I have the following an array object data. I wanted to filter it's data when a user provide either title, category or published values from an input. I can only filter the data only with title value. How can I make it to category and published values as well? here is my code. `

const data = [
  { id: 1, title: "Hunger games 2", category: "Action", published: "2013" },
  { id: 2, title: "Iron Man", category: "Action", published: "2013" },
];

const [searchValue, setSearchValue] = useState(""); //searchValue is an input value

const DisplayData = data
    ?.filter((row) => row?.title?.match(new RegExp(searchValue, "i")))
    ?.map((items) => {
      return (
        <>
          <tr key={items.id}>
            <td className="text-center">{items.title}</td>
            <td>{items.category}</td>
            <td>{items.published}</td>
          </tr>
        </>
      );
    });

CodePudding user response:

You can add "or" conditions to your filter:

const DisplayData = data
    ?.filter((row) => row?.title?.match(new RegExp(searchValue, "I")) || 
      row?.category?.match(new RegExp(searchValue, "I")) ||
      row?.published?.match(new RegExp(searchValue, "I"))
    )
    ?.map((items) => ...
  • Related