How to get the filtered data in bootstrap datatable while using React.js by entering in search box?

108 views Asked by At

I am using bootstrap datatable in my React application

function MyApp(){

const tableRef = useRef(null);
const [tableSave, setTableSave] = useState(null)
const [dataFromAPI, setDataFromAPI] = useState([])

useEffect(()=> {
      axios.get("url").then(response=>setDataFromAPI(response.data))
},[])
 
useEffect(() => {
    
   setTableSave($(tableRef.current).DataTable(
      {
        bSort: false,
        scrollY: "200px",
        scrollCollapse: true,
        info: true,
        paging: false
      }
    ));
   
  }, [dataFromAPI]);
return (
<>
 <table className="table" ref={tableRef}>
            <thead>
              <tr>
                <th>A</th>
                <th>B</th>
                <th>C</th>
              </tr>
            </thead>
            <tbody>
              {tableData.map((_value, i) => {
                return (
                  <tr key={i}>
                    <td key={i}>{_value['A']}</td>
                    <td key={i}>{_value['B']}</td>
                    <td key={i}>{_value['C']}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
</>
)
}

Now the data is properly displaying and also searching worked perfectly but I want the array when user enter search and filter the table records. I don't know which method is called in Bootstrap Datatable while working on react application. For example when user entered 'A' in search box, the method should be called and return an array with objects having 'A' value in any column. How this can be achieved by keeping the datatable features?

1

There are 1 answers

0
Ghias Ali On

Just got the answer

if(tableSave){
  tableSave.on("search.dt", function() {
      //filtered rows data as an arrays

      let data = tableSave.rows({ filter: "applied" }).data();

}

}

This function will be called on each input click in search bar and filtered data will be returned