SlideShare a Scribd company logo
React Table
Tutorial:
useFilter (Part 2)
www.bacancytechnology.com
In the previous blogpost of React Table
tutorial series, we learned how to get
started with React-table-tutorial-7 and
built a demo application using hook
useTable. Adding more to the react-table
tutorial series, we will now pick another
hook, useFilter, and implement it in the
same demo app, that we’ve built earlier.
So, I’d suggest going through my previous
blog, React Table Tutorial: Project Setup
and useTable, if you want to build the
application from scratch; here, we will only
implement the useFilter hook and explore
a bit about the same.
Overview
Remember how we used to implement
filtering in react-table v6 to v7? It was kind
of messy and too much to take care of. But,
thanks to react-table v7 for making it more
accessible, handy, and customizable. The
headless version of the react-table gives
you control for designing and maintaining
the table as per your requirements. Also,
Also, new features of the react-table make
the React table library lightweight and give
you opportunities to improve
performance.
React Table
Tutorial Goal:
useFilter
hook
https://youtu.be/5rXI5E9iCkE
Getting
started with
React Table
useFilter hook
Once, done with setting up the project
with the useTable hook, follow these steps
to implement useFilter and useGlobalFilter
in your project.
According to our UI, this will be the project
structure for the react-table example.
Update App.js & TableContainer.js
Create a new file named – Filter.js
(which will have functional
components for Filter views)
We will implement the default filter and
select column filter. For that, we will
Without further ado, let’s create Filter.js
and define React table components for
Filter UI.
Defining
Filter
Components
for UI
Default Filter for Columns: It will
render text input, and the column data
is filtered based on the text entered.
Global Filter: It will render text input
but not just for columns; the entire
table data is filtered based on the text
entered.
Select Filter for Column: It will render
select input, and the column data is
filtered based on the option selected
from the list.
In this React Table demo, we will
implement three filter views –
We will create a common file named
Filter.js (or with any suitable name) from
where we will export the above-mentioned
functional components for readability
purposes.
Filter.js
import { React, useMemo, useState }
from "react";
import { useAsyncDebounce } from
"react-table";
import { Label, Input } from
"reactstrap";
// Component for Global Filter
export function GlobalFilter({
globalFilter,
setGlobalFilter
}) {
const [value, setValue] =
useState(globalFilter);
const onChange =
useAsyncDebounce((value) => {
setGlobalFilter(value || undefined);
}, 200);
return (
<div>
<Label>Search Table: </Label>
<Input
value={value || ""}
onChange={(e) => {
setValue(e.target.value);
onChange(e.target.value);
}}
placeholder=" Enter value "
className="w-25"
style={{
fontSize: "1.1rem",
margin: "15px",
display: "inline",
}}
/>
</div>
);
}
// Component for Default Column Filter
export function
DefaultFilterForColumn({
column: {
filterValue,
preFilteredRows: { length },
setFilter,
},
}) {
return (
<Input
value={filterValue || ""}
onChange={(e) => {
// Set undefined to remove the filter
entirely
setFilter(e.target.value || undefined);
}}
placeholder={`Search ${length}
records..`}
style={{ marginTop: "10px" }}
/>
);
}
// Component for Custom Select Filter
export function SelectColumnFilter({
column: { filterValue, setFilter,
preFilteredRows, id },
}) {
// Use preFilteredRows to calculate
the options
const options = useMemo(() => {
const options = new Set();
preFilteredRows.forEach((row) => {
options.add(row.values[id]);
});
return [...options.values()];
}, [id, preFilteredRows]);
// UI for Multi-Select box
return (
<select
value={filterValue}
onChange={(e) => {
setFilter(e.target.value || undefined);
}}
>
<option value="">All</option>
{options.map((option, i) => (
<option key={i} value={option}>
{option}
</option>
))}
</select>
);
}
Explanation
What is the use of useAsyncDebounce? –
React table provides useAsyncDebounce to
avoid the multiple re-renders caused due
to side-effects and to use the latest one.
Back-to-back state side-effects take place
that triggers multiple renders. So, rather
than handling it manually, React Table
provides a hook to debounce the rapid
side-effects.
Here, we have little data, so that we won’t
realize the importance of
useAsyncDebounce. But, consider, if we
have thousands of data filtered, then the
continuous state changes and side-effects
are much costlier than this demo app.
A good developer takes care of the
performance even while coding for a
demo application. Try avoiding trash
coding.
The setfilter, filterValue, and
preFilterRows are column properties
used for specific columns. We have
destructured the column prop and
used them to get the filter values of
respective columns.
Rendering
Filter
components
For GlobalFilter and
DefaultFilterForColumn
Open TableContainer.js and Import
components and hooks-
import { useTable, useFilters,
useGlobalFilter } from "react-table";
import { GlobalFilter,
DefaultFilterForColumn} from "./Filter";
Pass DefaultFilter For Column to use Table
hook as a default filter for all the columns.
So by default, your columns will have these
components as filters unless you provide a
custom filter or disable the filter.
useTable( { columns, data,
defaultColumn: { Filter:
DefaultFilterForColumn }, }, useFilters,
useGlobalFilter
Now for rendering the UI, use the following code-
{/* Rendering Global Filter */}
<GlobalFilter
preGlobalFilteredRows=
{preGlobalFilteredRows}
globalFilter={state.globalFilter}
setGlobalFilter={setGlobalFilter}
/>
{/* Rendering Default Column Filter */}
<div>
{column.canFilter ? column.render("Filter") :
null}
</div>
Your entire TableContainer.js will look like
this-
import { React } from "react";
import { useTable, useFilters,
useGlobalFilter } from "react-table";
import { GlobalFilter, DefaultColumnFilter }
from "./Filter";
export default function Table({ columns,
data }) {
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
state,
visibleColumns,
prepareRow,
setGlobalFilter,
preGlobalFilteredRows,
} = useTable(
{
{
columns,
data,
defaultColumn: { Filter:
DefaultFilterForColumn },
},
useFilters,
useGlobalFilter
);
return (
<table {...getTableProps()}>
<thead>
<tr>
<th
colSpan={visibleColumns.length}
style={{
textAlign: "center",
}}
>
{/* Rendering Global Filter */}
<GlobalFilter
preGlobalFilteredRows=
{preGlobalFilteredRows}
globalFilter={state.globalFilter}
setGlobalFilter={setGlobalFilter}
/>
</th>
</tr>
{headerGroups.map((headerGroup)
=> (
<tr
{...headerGroup.getHeaderGroupProps
()}>
{headerGroup.headers.map((column)
=> (
<th
{...column.getHeaderProps()}>
{column.render("Header")}
{/* Rendering Default Column
Filter */}
<div>
{column.canFilter ?
column.render("Filter")
:null}
</div>
</th>
))}
</tr>
))}
</thead>
<tbody {...getTableBodyProps()}>
{rows.map((row, i) => {
prepareRow(row);
return (
<tr {...row.getRowProps()}>
{row.cells.map((cell) => {
return <td
{...cell.getCellProps()}>
{cell.render("Cell")}
</td>;
})}
</tr>
);
})}
</tbody>
</table>
);
}
Open App.js where we have defined the
array of columns.
Import SelectColumnFilter.
Add Filter: SelectColumnFilter to a
particular object of the column.
For using SelectColumnFilter,
{
Header: "Status", accessor: "show.status",
Filter: SelectColumnFilter, filter: "includes",
},
If you disable filter on any particular
column, add the following line of code-
{
Header: "Premiered", accessor:
"show.premiered", // disable the filter for
particular column disableFilters: true, Cell: ({
cell: { value } }) =&gt; value || "-",
},
How does
Column Filter
work in
React Table?
Do you remember we added a line for
implementing column filter-
<div>{column.canFilter ?
column.render("Filter") : null}</div>
The “Filter” is the property in the column
definition. It will render whichever
component is given as a value to the Filter
key.
Here we have used defaultcolumn, so no
need to define Filter for all the columns but
we have to define the Filter key for custom
filters (e.g. SelectColumnFilter)
The condition of column.canFilter will be
executed and it will render component
defined to key Filter.
Here we have mentioned the custom filter,
SelectColumnFilter, in the object and set
DefaultFilterForColumn as a default shown
filter.
The entire source code is available at
Github Repository. Feel free to clone and
play around with the code.
Conclusion
So, this was about how to filter your
table data using the useFilter hook. I
hope the React Table tutorial was
helpful for you. If you have any
questions or suggestions, feel free to
comment below.
If you are a ReactJs enthusiast, check
the ReactJS Tutorials page with more
tutorials and its respective github
repository.
At Bacancy Technology, developers try
their best to come up with optimum
solutions and affordable problem-
solving approaches. If you are looking
for a helping hand for your project,
contact us to hire ReactJS developers
without wasting a minute.
Thank You
www.bacancytechnology.com
Ad

Recommended

Java script ppt
Java script ppt
The Health and Social Care Information Centre
 
004 - JavaFX Tutorial - Event Handling
004 - JavaFX Tutorial - Event Handling
Mohammad Hossein Rimaz
 
How Hashmap works internally in java
How Hashmap works internally in java
Ramakrishna Joshi
 
multi threading
multi threading
Yaswanth Babu Gummadivelli
 
Collections in Java Notes
Collections in Java Notes
Shalabh Chaudhary
 
Java J2EE Complete Syllabus Checklist
Java J2EE Complete Syllabus Checklist
Sunil Kumar Gunasekaran
 
Java program structure
Java program structure
shalinikarunakaran1
 
Polymorphism in Java by Animesh Sarkar
Polymorphism in Java by Animesh Sarkar
Animesh Sarkar
 
Callback Function
Callback Function
Roland San Nicolas
 
3. jvm
3. jvm
Indu Sharma Bhardwaj
 
Java I/O
Java I/O
Jussi Pohjolainen
 
Java 8 Lambda Expressions
Java 8 Lambda Expressions
Scott Leberknight
 
Control structures in java
Control structures in java
VINOTH R
 
Asp.net caching
Asp.net caching
Mindfire Solutions
 
Introduction to Javascript
Introduction to Javascript
Amit Tyagi
 
VB.Net GUI Unit_01
VB.Net GUI Unit_01
Prashanth Shivakumar
 
Java
Java
Tony Nguyen
 
JavaScript Tutorial
JavaScript Tutorial
Bui Kiet
 
Html5 and-css3-overview
Html5 and-css3-overview
Jacob Nelson
 
Nuxt.JS Introdruction
Nuxt.JS Introdruction
David Ličen
 
Exception Handling In Java
Exception Handling In Java
parag
 
Basic of Multithreading in JAva
Basic of Multithreading in JAva
suraj pandey
 
Threads in Java
Threads in Java
Gaurav Aggarwal
 
types of events in JS
types of events in JS
chauhankapil
 
Java JVM Memory Cheat Sheet
Java JVM Memory Cheat Sheet
Mark Papis
 
Operators in java
Operators in java
AbhishekMondal42
 
Ict u5
Ict u5
Dr. C.V. Suresh Babu
 
VB.net
VB.net
PallaviKadam
 
React table tutorial project setup, use table, and usefilter
React table tutorial project setup, use table, and usefilter
Katy Slemon
 
Advantage of Table in React JS.pdf
Advantage of Table in React JS.pdf
Nishaadequateinfosof
 

More Related Content

What's hot (20)

Callback Function
Callback Function
Roland San Nicolas
 
3. jvm
3. jvm
Indu Sharma Bhardwaj
 
Java I/O
Java I/O
Jussi Pohjolainen
 
Java 8 Lambda Expressions
Java 8 Lambda Expressions
Scott Leberknight
 
Control structures in java
Control structures in java
VINOTH R
 
Asp.net caching
Asp.net caching
Mindfire Solutions
 
Introduction to Javascript
Introduction to Javascript
Amit Tyagi
 
VB.Net GUI Unit_01
VB.Net GUI Unit_01
Prashanth Shivakumar
 
Java
Java
Tony Nguyen
 
JavaScript Tutorial
JavaScript Tutorial
Bui Kiet
 
Html5 and-css3-overview
Html5 and-css3-overview
Jacob Nelson
 
Nuxt.JS Introdruction
Nuxt.JS Introdruction
David Ličen
 
Exception Handling In Java
Exception Handling In Java
parag
 
Basic of Multithreading in JAva
Basic of Multithreading in JAva
suraj pandey
 
Threads in Java
Threads in Java
Gaurav Aggarwal
 
types of events in JS
types of events in JS
chauhankapil
 
Java JVM Memory Cheat Sheet
Java JVM Memory Cheat Sheet
Mark Papis
 
Operators in java
Operators in java
AbhishekMondal42
 
Ict u5
Ict u5
Dr. C.V. Suresh Babu
 
VB.net
VB.net
PallaviKadam
 

Similar to React table tutorial use filter (part 2) (12)

React table tutorial project setup, use table, and usefilter
React table tutorial project setup, use table, and usefilter
Katy Slemon
 
Advantage of Table in React JS.pdf
Advantage of Table in React JS.pdf
Nishaadequateinfosof
 
Thinking in react
Thinking in react
aashimadudeja
 
React JS & Functional Programming Principles
React JS & Functional Programming Principles
Andrii Lundiak
 
How to perform debounce in react
How to perform debounce in react
BOSC Tech Labs
 
Advantages and Disadvantage of table in react js-technical chamber.pdf
Advantages and Disadvantage of table in react js-technical chamber.pdf
Nishaadequateinfosof
 
JavaScript ES10 and React Js Introduction
JavaScript ES10 and React Js Introduction
Amanpreet Singh
 
Advanced React Component Patterns - ReactNext 2018
Advanced React Component Patterns - ReactNext 2018
Robert Herbst
 
A comprehensive guide on developing responsive and common react filter component
A comprehensive guide on developing responsive and common react filter component
Katy Slemon
 
Mobx - performance and sanity
Mobx - performance and sanity
500Tech
 
Why React's Awesome!
Why React's Awesome!
nomanalikk
 
React JS Workings Exercises Extra Classes
React JS Workings Exercises Extra Classes
ssuser426fcf
 
React table tutorial project setup, use table, and usefilter
React table tutorial project setup, use table, and usefilter
Katy Slemon
 
Advantage of Table in React JS.pdf
Advantage of Table in React JS.pdf
Nishaadequateinfosof
 
React JS & Functional Programming Principles
React JS & Functional Programming Principles
Andrii Lundiak
 
How to perform debounce in react
How to perform debounce in react
BOSC Tech Labs
 
Advantages and Disadvantage of table in react js-technical chamber.pdf
Advantages and Disadvantage of table in react js-technical chamber.pdf
Nishaadequateinfosof
 
JavaScript ES10 and React Js Introduction
JavaScript ES10 and React Js Introduction
Amanpreet Singh
 
Advanced React Component Patterns - ReactNext 2018
Advanced React Component Patterns - ReactNext 2018
Robert Herbst
 
A comprehensive guide on developing responsive and common react filter component
A comprehensive guide on developing responsive and common react filter component
Katy Slemon
 
Mobx - performance and sanity
Mobx - performance and sanity
500Tech
 
Why React's Awesome!
Why React's Awesome!
nomanalikk
 
React JS Workings Exercises Extra Classes
React JS Workings Exercises Extra Classes
ssuser426fcf
 
Ad

More from Katy Slemon (20)

React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
Katy Slemon
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdf
Katy Slemon
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdf
Katy Slemon
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdf
Katy Slemon
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdf
Katy Slemon
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
Katy Slemon
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdf
Katy Slemon
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdf
Katy Slemon
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Katy Slemon
 
How to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdf
Katy Slemon
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdf
Katy Slemon
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdf
Katy Slemon
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
Katy Slemon
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdf
Katy Slemon
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
Katy Slemon
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Katy Slemon
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdf
Katy Slemon
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdf
Katy Slemon
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
Katy Slemon
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdf
Katy Slemon
 
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
Katy Slemon
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdf
Katy Slemon
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdf
Katy Slemon
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdf
Katy Slemon
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdf
Katy Slemon
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
Katy Slemon
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdf
Katy Slemon
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdf
Katy Slemon
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Katy Slemon
 
How to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdf
Katy Slemon
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdf
Katy Slemon
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdf
Katy Slemon
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
Katy Slemon
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdf
Katy Slemon
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
Katy Slemon
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Katy Slemon
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdf
Katy Slemon
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdf
Katy Slemon
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
Katy Slemon
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdf
Katy Slemon
 
Ad

Recently uploaded (20)

AI vs Human Writing: Can You Tell the Difference?
AI vs Human Writing: Can You Tell the Difference?
Shashi Sathyanarayana, Ph.D
 
Python Conference Singapore - 19 Jun 2025
Python Conference Singapore - 19 Jun 2025
ninefyi
 
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Priyanka Aash
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
 
“MPU+: A Transformative Solution for Next-Gen AI at the Edge,” a Presentation...
“MPU+: A Transformative Solution for Next-Gen AI at the Edge,” a Presentation...
Edge AI and Vision Alliance
 
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
The Future of Product Management in AI ERA.pdf
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Priyanka Aash
 
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
Fwdays
 
Securing AI - There Is No Try, Only Do!.pdf
Securing AI - There Is No Try, Only Do!.pdf
Priyanka Aash
 
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Safe Software
 
Curietech AI in action - Accelerate MuleSoft development
Curietech AI in action - Accelerate MuleSoft development
shyamraj55
 
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
Priyanka Aash
 
Lessons Learned from Developing Secure AI Workflows.pdf
Lessons Learned from Developing Secure AI Workflows.pdf
Priyanka Aash
 
Connecting Data and Intelligence: The Role of FME in Machine Learning
Connecting Data and Intelligence: The Role of FME in Machine Learning
Safe Software
 
Daily Lesson Log MATATAG ICT TEchnology 8
Daily Lesson Log MATATAG ICT TEchnology 8
LOIDAALMAZAN3
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Priyanka Aash
 
AI vs Human Writing: Can You Tell the Difference?
AI vs Human Writing: Can You Tell the Difference?
Shashi Sathyanarayana, Ph.D
 
Python Conference Singapore - 19 Jun 2025
Python Conference Singapore - 19 Jun 2025
ninefyi
 
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Priyanka Aash
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
 
“MPU+: A Transformative Solution for Next-Gen AI at the Edge,” a Presentation...
“MPU+: A Transformative Solution for Next-Gen AI at the Edge,” a Presentation...
Edge AI and Vision Alliance
 
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
The Future of Product Management in AI ERA.pdf
The Future of Product Management in AI ERA.pdf
Alyona Owens
 
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Cracking the Code - Unveiling Synergies Between Open Source Security and AI.pdf
Priyanka Aash
 
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
Fwdays
 
Securing AI - There Is No Try, Only Do!.pdf
Securing AI - There Is No Try, Only Do!.pdf
Priyanka Aash
 
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Safe Software
 
Curietech AI in action - Accelerate MuleSoft development
Curietech AI in action - Accelerate MuleSoft development
shyamraj55
 
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
Priyanka Aash
 
Lessons Learned from Developing Secure AI Workflows.pdf
Lessons Learned from Developing Secure AI Workflows.pdf
Priyanka Aash
 
Connecting Data and Intelligence: The Role of FME in Machine Learning
Connecting Data and Intelligence: The Role of FME in Machine Learning
Safe Software
 
Daily Lesson Log MATATAG ICT TEchnology 8
Daily Lesson Log MATATAG ICT TEchnology 8
LOIDAALMAZAN3
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Priyanka Aash
 

React table tutorial use filter (part 2)

  • 1. React Table Tutorial: useFilter (Part 2) www.bacancytechnology.com
  • 2. In the previous blogpost of React Table tutorial series, we learned how to get started with React-table-tutorial-7 and built a demo application using hook useTable. Adding more to the react-table tutorial series, we will now pick another hook, useFilter, and implement it in the same demo app, that we’ve built earlier. So, I’d suggest going through my previous blog, React Table Tutorial: Project Setup and useTable, if you want to build the application from scratch; here, we will only implement the useFilter hook and explore a bit about the same.
  • 4. Remember how we used to implement filtering in react-table v6 to v7? It was kind of messy and too much to take care of. But, thanks to react-table v7 for making it more accessible, handy, and customizable. The headless version of the react-table gives you control for designing and maintaining the table as per your requirements. Also, Also, new features of the react-table make the React table library lightweight and give you opportunities to improve performance.
  • 8. Once, done with setting up the project with the useTable hook, follow these steps to implement useFilter and useGlobalFilter in your project. According to our UI, this will be the project structure for the react-table example.
  • 9. Update App.js & TableContainer.js Create a new file named – Filter.js (which will have functional components for Filter views) We will implement the default filter and select column filter. For that, we will Without further ado, let’s create Filter.js and define React table components for Filter UI.
  • 11. Default Filter for Columns: It will render text input, and the column data is filtered based on the text entered. Global Filter: It will render text input but not just for columns; the entire table data is filtered based on the text entered. Select Filter for Column: It will render select input, and the column data is filtered based on the option selected from the list. In this React Table demo, we will implement three filter views – We will create a common file named Filter.js (or with any suitable name) from where we will export the above-mentioned functional components for readability purposes.
  • 12. Filter.js import { React, useMemo, useState } from "react"; import { useAsyncDebounce } from "react-table"; import { Label, Input } from "reactstrap"; // Component for Global Filter export function GlobalFilter({ globalFilter, setGlobalFilter }) { const [value, setValue] = useState(globalFilter); const onChange = useAsyncDebounce((value) => { setGlobalFilter(value || undefined); }, 200);
  • 13. return ( <div> <Label>Search Table: </Label> <Input value={value || ""} onChange={(e) => { setValue(e.target.value); onChange(e.target.value); }} placeholder=" Enter value " className="w-25" style={{ fontSize: "1.1rem", margin: "15px", display: "inline", }} /> </div> ); }
  • 14. // Component for Default Column Filter export function DefaultFilterForColumn({ column: { filterValue, preFilteredRows: { length }, setFilter, }, }) { return ( <Input value={filterValue || ""} onChange={(e) => { // Set undefined to remove the filter entirely setFilter(e.target.value || undefined); }} placeholder={`Search ${length} records..`} style={{ marginTop: "10px" }} /> ); }
  • 15. // Component for Custom Select Filter export function SelectColumnFilter({ column: { filterValue, setFilter, preFilteredRows, id }, }) { // Use preFilteredRows to calculate the options const options = useMemo(() => { const options = new Set(); preFilteredRows.forEach((row) => { options.add(row.values[id]); }); return [...options.values()]; }, [id, preFilteredRows]);
  • 16. // UI for Multi-Select box return ( <select value={filterValue} onChange={(e) => { setFilter(e.target.value || undefined); }} > <option value="">All</option> {options.map((option, i) => ( <option key={i} value={option}> {option} </option> ))} </select> ); }
  • 17. Explanation What is the use of useAsyncDebounce? – React table provides useAsyncDebounce to avoid the multiple re-renders caused due to side-effects and to use the latest one. Back-to-back state side-effects take place that triggers multiple renders. So, rather than handling it manually, React Table provides a hook to debounce the rapid side-effects. Here, we have little data, so that we won’t realize the importance of useAsyncDebounce. But, consider, if we have thousands of data filtered, then the continuous state changes and side-effects are much costlier than this demo app.
  • 18. A good developer takes care of the performance even while coding for a demo application. Try avoiding trash coding. The setfilter, filterValue, and preFilterRows are column properties used for specific columns. We have destructured the column prop and used them to get the filter values of respective columns.
  • 20. For GlobalFilter and DefaultFilterForColumn Open TableContainer.js and Import components and hooks- import { useTable, useFilters, useGlobalFilter } from "react-table"; import { GlobalFilter, DefaultFilterForColumn} from "./Filter"; Pass DefaultFilter For Column to use Table hook as a default filter for all the columns. So by default, your columns will have these components as filters unless you provide a custom filter or disable the filter.
  • 21. useTable( { columns, data, defaultColumn: { Filter: DefaultFilterForColumn }, }, useFilters, useGlobalFilter Now for rendering the UI, use the following code- {/* Rendering Global Filter */} <GlobalFilter preGlobalFilteredRows= {preGlobalFilteredRows} globalFilter={state.globalFilter} setGlobalFilter={setGlobalFilter} /> {/* Rendering Default Column Filter */} <div> {column.canFilter ? column.render("Filter") : null} </div>
  • 22. Your entire TableContainer.js will look like this- import { React } from "react"; import { useTable, useFilters, useGlobalFilter } from "react-table"; import { GlobalFilter, DefaultColumnFilter } from "./Filter"; export default function Table({ columns, data }) { const { getTableProps, getTableBodyProps, headerGroups, rows, state, visibleColumns, prepareRow, setGlobalFilter, preGlobalFilteredRows, } = useTable( {
  • 23. { columns, data, defaultColumn: { Filter: DefaultFilterForColumn }, }, useFilters, useGlobalFilter ); return ( <table {...getTableProps()}> <thead> <tr> <th colSpan={visibleColumns.length} style={{ textAlign: "center", }} >
  • 24. {/* Rendering Global Filter */} <GlobalFilter preGlobalFilteredRows= {preGlobalFilteredRows} globalFilter={state.globalFilter} setGlobalFilter={setGlobalFilter} /> </th> </tr> {headerGroups.map((headerGroup) => ( <tr {...headerGroup.getHeaderGroupProps ()}> {headerGroup.headers.map((column) => ( <th {...column.getHeaderProps()}> {column.render("Header")} {/* Rendering Default Column Filter */} <div> {column.canFilter ? column.render("Filter")
  • 25. :null} </div> </th> ))} </tr> ))} </thead> <tbody {...getTableBodyProps()}> {rows.map((row, i) => { prepareRow(row); return ( <tr {...row.getRowProps()}> {row.cells.map((cell) => { return <td {...cell.getCellProps()}> {cell.render("Cell")}
  • 26. </td>; })} </tr> ); })} </tbody> </table> ); } Open App.js where we have defined the array of columns. Import SelectColumnFilter. Add Filter: SelectColumnFilter to a particular object of the column. For using SelectColumnFilter,
  • 27. { Header: "Status", accessor: "show.status", Filter: SelectColumnFilter, filter: "includes", }, If you disable filter on any particular column, add the following line of code- { Header: "Premiered", accessor: "show.premiered", // disable the filter for particular column disableFilters: true, Cell: ({ cell: { value } }) =&gt; value || "-", },
  • 28. How does Column Filter work in React Table?
  • 29. Do you remember we added a line for implementing column filter- <div>{column.canFilter ? column.render("Filter") : null}</div> The “Filter” is the property in the column definition. It will render whichever component is given as a value to the Filter key. Here we have used defaultcolumn, so no need to define Filter for all the columns but we have to define the Filter key for custom filters (e.g. SelectColumnFilter)
  • 30. The condition of column.canFilter will be executed and it will render component defined to key Filter. Here we have mentioned the custom filter, SelectColumnFilter, in the object and set DefaultFilterForColumn as a default shown filter. The entire source code is available at Github Repository. Feel free to clone and play around with the code.
  • 32. So, this was about how to filter your table data using the useFilter hook. I hope the React Table tutorial was helpful for you. If you have any questions or suggestions, feel free to comment below. If you are a ReactJs enthusiast, check the ReactJS Tutorials page with more tutorials and its respective github repository. At Bacancy Technology, developers try their best to come up with optimum solutions and affordable problem- solving approaches. If you are looking for a helping hand for your project, contact us to hire ReactJS developers without wasting a minute.