How can I filter a table with select options in React (component function)?

7.1k Views Asked by At

I can't find how to filter a table in React with the Select (dropdown). I found an example on Google but they used Node but their code doesn't work on my React app. I prefer using components not class functions. This is my code. And I want to filter the table exemple by select options?:

const [data, getData] = useState([])
const URL = 'https://jsonplaceholder.typicode.com/posts'
useEffect(() => {
fetchData()
}, [])

const fetchData = () => {
fetch(URL)
    .then((res) =>
        res.json())

    .then((response) => {
        console.log(response);
        getData(response);
    })

  }

  return (
  <>
    <Select options=["A","B","C"] />
    <table>
        <tr>
            <th>User Id</th>
            <th>Id</th>
            <th>Title</th>
            <th>Description</th>
        </tr>
        {data.map((item, i) => (
            <tr key={i}>
                <td>{item.userId}</td>
                <td>{item.id}</td>
                <td>{item.title}</td>
                <td>{item.body}</td>
            </tr>
         </table>
      </>
2

There are 2 best solutions below

2
hpertaia On
  1. Since you didn't specify which property to filter by, I filtered by id.
  2. You didn't specify which select component you are using. Hence, I've replaced your select with Native HTML Select

In short, in order to filter by selected option you have to:

  1. Use the onchange event on the select (all the non-native select components like Material-ui, etc. also have it). You have to have a handler that assigns a UseState variable to the value selected.
  2. In render method, you have to use Array.filter to filter by the preserved value.

Here is the working code:

import "./styles.css";
import React, { useEffect, useState } from "react";

export default function App() {
  const [data, getData] = useState([]);
  const [selectedId, setSelectedId] = useState([]);
  const URL = "https://jsonplaceholder.typicode.com/posts";
  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = () => {
    fetch(URL)
      .then((res) => res.json())

      .then((response) => {
        console.log(response);
        getData(response);
      });
  };

  const handleSelectChange = (e) => {
    console.log(e.target.value);
    setSelectedId(e.target.value);
  };

  return (
    <>
      <select onChange={handleSelectChange} name="ids" id="ids">
        <option value="1">Id 1</option>
        <option value="2">Id 2</option>
        <option value="3">Id 3</option>
        <option value="4">Id 4</option>
      </select>
      <table>
        <tr>
          <th>User Id</th>
          <th>Id</th>
          <th>Title</th>
          <th>Description</th>
        </tr>
        {data
          .filter((value) => {
            return Number(value.id) === Number(selectedId);
          })
          .map((item, i) => (
            <tr key={i}>
              <td>{item.userId}</td>
              <td>{item.id}</td>
              <td>{item.title}</td>
              <td>{item.body}</td>
            </tr>
          ))}
      </table>
    </>
  );
}

Working Sandbox: https://codesandbox.io/s/wonderful-feistel-qgrm0f?file=/src/App.js

0
Sanjeev Maurya On

To filter a table with select options in a React functional component, you can follow these steps:

  1. Set up your component's state: Define state variables for the table data and the selected filter option.

import React, { useState } from 'react';

function TableFilter() {
  const [tableData, setTableData] = useState([]);
  const [selectedFilter, setSelectedFilter] = useState('');

  // Rest of the component code
}

  1. Fetch or set the initial table data: You can use the useEffect hook to fetch or set the initial table data when the component mounts.

import React, { useState, useEffect } from 'react';

function TableFilter() {
  const [tableData, setTableData] = useState([]);
  const [selectedFilter, setSelectedFilter] = useState('');

  useEffect(() => {
    // Fetch or set the initial table data
    // Example:
    const fetchData = async () => {
      const response = await fetch('api/table-data');
      const data = await response.json();
      setTableData(data);
    };

    fetchData();
  }, []);

  // Rest of the component code
}

  1. Create the select options: Render the select element with options for filtering the table.

import React, { useState, useEffect } from 'react';

function TableFilter() {
  const [tableData, setTableData] = useState([]);
  const [selectedFilter, setSelectedFilter] = useState('');

  useEffect(() => {
    // Fetch or set the initial table data
    // Example:
    const fetchData = async () => {
      const response = await fetch('api/table-data');
      const data = await response.json();
      setTableData(data);
    };

    fetchData();
  }, []);

  const handleFilterChange = (event) => {
    setSelectedFilter(event.target.value);
  };

  return (
    <div>
      <label htmlFor="filter">Filter:</label>
      <select id="filter" value={selectedFilter} onChange={handleFilterChange}>
        <option value="">All</option>
        <option value="option1">Option 1</option>
        <option value="option2">Option 2</option>
        {/* Add more options as needed */}
      </select>

      {/* Table rendering goes here */}
    </div>
  );
}

  1. Filter and render the table: Use the selected filter value to filter the table data and render the filtered rows.

import React, { useState, useEffect } from 'react';

function TableFilter() {
  const [tableData, setTableData] = useState([]);
  const [selectedFilter, setSelectedFilter] = useState('');

  useEffect(() => {
    // Fetch or set the initial table data
    // Example:
    const fetchData = async () => {
      const response = await fetch('api/table-data');
      const data = await response.json();
      setTableData(data);
    };

    fetchData();
  }, []);

  const handleFilterChange = (event) => {
    setSelectedFilter(event.target.value);
  };

  const filteredData = selectedFilter
    ? tableData.filter((row) => row.option === selectedFilter)
    : tableData;

  return (
    <div>
      <label htmlFor="filter">Filter:</label>
      <select id="filter" value={selectedFilter} onChange={handleFilterChange}>
        <option value="">All</option>
        <option value="option1">Option 1</option>
        <option value="option2">Option 2</option>
        {/* Add more options as needed */}
      </select>

      <table>
        <thead>
          <tr>
            <th>Column