Skip to main content

How to make search filter for each column in html table in react

I have a HTML table which I made from scratch and rendering it with APIs data, I did all the pagination sorting and other stuffs but now I am trying to do search filter for each column.

I made one global search filter which works totally fine but facing issue with the making search for each column.

What I am doing

  • Below is my HTML table component

             <HTMLTable
               tableData={tData} // here passing data as tData
               tableClass="table"
               theadClass="theadClass"
               tbodyClass="tbodyClass"
             />
    
  • What I am doing is getting data from api and creating one state and updating it in useEffect when page loads as empty array dependency like below

     const [searchData, setsearchData] = useState(null);
     useEffect(() => {
     setsearchData(data); // here updating my state with the api data
     }, []);
    
  • Now below is my logic I am using to filter the data

    const table_data =
     searchData &&
     searchData.filter((item) => {
     return (
     item[context.columnTypedInto] // here whichever column user types I am passing it as 
     context
       ?.toString() // writing the logic for number
       .toLowerCase()
       .includes(context.SearchValue.toLowerCase()) || // when user types anything I am 
       saving it in context and passing it here
      !context.SearchValue
       );
    });
    
  • So About the above code, i have created a context when user types in any of the column I know which column they are typing into so that is context.columnTypedInto and what user is typing that too I am storing into a context which is context.SearchValue so this works fine

  • Now What i am trying to do is when user is typing anything I am getting that related data and updating my state setsearchData which works fine, below is the code

     useEffect(() => {
     setsearchData(table_data);
    }, [context.SearchValue]); 
    

SO whenever search value changes this code will run and it is working fine if I type in any column and search then I type in another column it search for the first searched data only not the whole data.

Issue I am facing

What issue I am facing is, whenever I am press backspace it won't work because the latest data in state is what I typed the last, so when I presss backspace I want it to take the previous data and when nothing is there the whole data should show.

That is the only part I am left with, I hope I have explained it well, if not, I will take the inputs and explain my issue again.

Edit/Update

I tried the below answer updated by @jantimon but that is not working, here is my code sandbox

Below I am explaining the full scenario

  • When I type in first_name column lets say I typed Jeanette so below is the data for this
  • 1 Jeanette Penddreth jpenddreth0@census.gov Female 26.58.193.2
  • Now If I type Giavani in first_name column it should show empty table because now the data is just one row, and when I press backspace it retain the data step-by-step
  • Before this edit When I type in firstname and then search for other it shows empty table which is totally fine but when I press backspace it is not taking the last data.

I have updated the codeSand box please do check.

i am trying to implement like this

Via Active questions tagged javascript - Stack Overflow https://ift.tt/OdwRuxv

Comments

Popular posts from this blog

ValueError: X has 10 features, but LinearRegression is expecting 1 features as input

So, I am trying to predict the model but its throwing error like it has 10 features but it expacts only 1. So I am confused can anyone help me with it? more importantly its not working for me when my friend runs it. It works perfectly fine dose anyone know the reason about it? cv = KFold(n_splits = 10) all_loss = [] for i in range(9): # 1st for loop over polynomial orders poly_order = i X_train = make_polynomial(x, poly_order) loss_at_order = [] # initiate a set to collect loss for CV for train_index, test_index in cv.split(X_train): print('TRAIN:', train_index, 'TEST:', test_index) X_train_cv, X_test_cv = X_train[train_index], X_test[test_index] t_train_cv, t_test_cv = t[train_index], t[test_index] reg.fit(X_train_cv, t_train_cv) loss_at_order.append(np.mean((t_test_cv - reg.predict(X_test_cv))**2)) # collect loss at fold all_loss.append(np.mean(loss_at_order)) # collect loss at order plt.plot(np.log(al...

Sorting large arrays of big numeric stings

I was solving bigSorting() problem from hackerrank: Consider an array of numeric strings where each string is a positive number with anywhere from to digits. Sort the array's elements in non-decreasing, or ascending order of their integer values and return the sorted array. I know it works as follows: def bigSorting(unsorted): return sorted(unsorted, key=int) But I didnt guess this approach earlier. Initially I tried below: def bigSorting(unsorted): int_unsorted = [int(i) for i in unsorted] int_sorted = sorted(int_unsorted) return [str(i) for i in int_sorted] However, for some of the test cases, it was showing time limit exceeded. Why is it so? PS: I dont know exactly what those test cases were as hacker rank does not reveal all test cases. source https://stackoverflow.com/questions/73007397/sorting-large-arrays-of-big-numeric-stings

How to load Javascript with imported modules?

I am trying to import modules from tensorflowjs, and below is my code. test.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title </head> <body> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.0.0/dist/tf.min.js"></script> <script type="module" src="./test.js"></script> </body> </html> test.js import * as tf from "./node_modules/@tensorflow/tfjs"; import {loadGraphModel} from "./node_modules/@tensorflow/tfjs-converter"; const MODEL_URL = './model.json'; const model = await loadGraphModel(MODEL_URL); const cat = document.getElementById('cat'); model.execute(tf.browser.fromPixels(cat)); Besides, I run the server using python -m http.server in my command prompt(Windows 10), and this is the error prompt in the console log of my browser: Failed to loa...