Home > OS >  Filtering locally rendered JSON table in React
Filtering locally rendered JSON table in React

Time:05-02

I have a page in my React App that renders some locally stored JSON Data into a table. I've been trying for a long time to implement a search bar that will filter through the PostCode column in the table and return the row. So far I've been able to make a search bar that does what I want it to but I haven't been able to integrate it into the page with the table.

My apologies if this is an easy question or I'm way off the mark. I'm a coding novice but have to use React for a project and struggle to get to grips with it.

The code for my table looks like this:


import SearchBar from './SearchBar'
import React,{useState,useEffect} from 'react';
import './App.css';
import { Data } from './NewData.js'

export const JsonReader = () => {
  return (
    <>
    
    <ArchiveHeader />

      <div className="data-container">Welcome to RF</div>
        {Data.map((data, key) => {
          return (
            <div key={key}>
            <JsonTable
            key = {key}
            Username = {data.Username}
            Address = {data.Address}
            PostCode = {data.PostCode}
            Details ={data.Details}
            Date ={data.Date}
            Score ={data.Score}
             />
             </div>
          );
        })}
    </>
  );
};

const ArchiveHeader = () => {
  return (
    <header className="ArchiveHeader">
      <h2>Rent Flag</h2>
    </header>
  );
};

const JsonTable= ({ Username, Address, PostCode, Details, Date, Score }) => {
  if (!Username) return <div />;
  return (
    <table data={Data}>
      <tbody>
        <tr>
          <td>
            <h5>{Username}</h5>
          </td>
          <td>
            <h5>{Address}</h5>
          </td>
          <td>
            <h4>{PostCode}</h4>
          </td>
          <td>
            <p>{Details}</p>
          </td>
          <td>
            <p>{Date}</p>
          </td>
          <td>
            <p>{Score}</p>
          </td>
        </tr>
      </tbody>
    </table>
  );
};
export default JsonReader;

and the code for my searchbar looks like this:

import Papa from "papaparse";
import React, { useState, useEffect } from 'react';
import { Data } from './NewData.js'
import JsonReader from './JsonReader'

export default function SearchBar () {
const [searchTerm,setSearchTerm] = useState('')
return (
  <div className="SearchBar">
    <input type="text" placeholder="search..." onChange={e=>setSearchTerm(e.target.value)} />
    {Data.filter((val)=>{
      if(searchTerm == ""){
        return val
      }
      else if(val.PostCode.toLowerCase().includes(searchTerm.toLowerCase())){
        return val;
      }
    }).map((val,key)=>{
      return <div>{val.PostCode} </div>
    })}
  </div>
);
}

CodePudding user response:

You can use useMemo hook for this functionality.

const searchResults = useMemo(() => {
  if (!searchTerm) {
    return items;
  }

  return Data?.filter((item) =>
    item?.toLowerCase()?.includes(searchTerm?.toLowerCase().trim())
  );
}, [Data, searchTerm]);

You can use searchResults variable and render that in your table.

CodePudding user response:

In the same JsonReader function you should:

  1. Create the useState constants [searchTerm, setSearchTerm].

  2. Set a new FData array with filtered data and that is the one you should do the mapping to.

  3. Place the input field on the same page.

  4. And, instead of using the Data.map you will use the FData.map.

This is how your JsonReader function should look like (and the SearchBar function could be discarded):

export const JsonReader = () => {
    const [searchTerm, setSearchTerm] = useState("");
    const FData = Data.filter((val) => {
    if (searchTerm == "") {
        return val;
    } else if (val.PostCode.toLowerCase().includes(searchTerm.toLowerCase())) {
        return val;
    }
    });
    return (
    <>
    
        <ArchiveHeader />

        <div className="data-container">Welcome to RF</div>
        <input type="text" placeholder="search..." onChange={(e) => setSearchTerm(e.target.value)} />
        {FData.map((data, key) => {
        return (
            <div key={key}>
            <JsonTable
                key = {key}
                Username = {data.Username}
                Address = {data.Address}
                PostCode = {data.PostCode}
                Details ={data.Details}
                Date ={data.Date}
                Score ={data.Score}
            />
            </div>
        );
        })}
    </>
    );
};
  • Related