Home > Blockchain >  how to use Date range filter in reactjs
how to use Date range filter in reactjs

Time:12-06

I am working with reactjs with axios and APIs and want to use date range filter in my data table. but its not working. please give me a example if anyone know or work on date range filter

enter image description here

CodePudding user response:

If you are doing the filter on frontend side, you can introduce an array filter method right before your .map which draws your table rows. The following might help you:

...
const [dateFilter, setDateFilter] = useState({
  startDate: null,
  endDate: null
})
//make sure to change these states with your filter header (the 2 inputs with type="date")

return (
  ...

<tbody>
{data
  .filter(row => {
    let filterPass = true
    const date = new Date(row.dateYouWannaFilterWith)
    if (dateFilter.startDate) {
      filterPass = filterPass && (new Date(dateFilter.startDate) < date)
    }
    if (dateFilter.endDate) {
      filterPass = filterPass && (new Date(dateFilter.endDate) > date)
    }
    //if filterPass comes back `false` the row is filtered out
    return filterPass
  })
    .map(row =>
      <tr>
        <td>Your</td>
        <td>Table</td>
        <td>Row</td>
        <td>Cells</td>
      </tr>
    )
}
</tbody >

This way you're fecthing all the rows and your UI is doing the filter.

Alternatively you could refetch the data everytime, with filter dates in query params of your request, and your backend could handle the filtering server side, only returning the rows you need. This way you need to configure the backend. And your frontend keeps refetching with different query param values.

await fetch('your-api-url?startDate=2021-12-06T03:40:32.242Z&endDate=2021-12-06T03:40:53.584Z')
//these dates are for placeholders
  • Related