This tutorial is part 2 of 2 in this series.
In this tutorial, I want to show you how to use React Table Library with a search feature. In the previous example, you have already installed React Table Library to create a table component. Now, we will enable users to search data in the table.
React Table Library does not come with a native search feature, however, since you have access to the data from the outside, you can manipulate it before passing it to the table. Let's see how this works.
First, create a new React useState Hook -- which holds the state of the search -- and a new event handler -- which acts as a callback function for the user interaction later on:
const App = () => {const [search, setSearch] = React.useState('');const handleSearch = (event) => {setSearch(event.target.value);};...};
Next, to the Table component, or somewhere entirely else if you want, add an HTML input field for setting the search state:
const App = () => {...return (<><label htmlFor="search">Search by Task:<input id="search" type="text" onChange={handleSearch} /></label><Table data={data}>...</Table></>);};
The search state is working. Finally search the list of items (here: nodes) before it reaches the Table component:
const App = () => {const [search, setSearch] = React.useState('');const handleSearch = (event) => {setSearch(event.target.value);};const data = {nodes: nodes.filter((item) =>item.name.includes(search)),};return (<><label htmlFor="search">Search by Task:<input id="search" type="text" onChange={handleSearch} /></label><Table data={data}>...</Table></>);};
That's it. If you want your table to search case insensitive, you have to adapt the filter function:
const data = {nodes: nodes.filter((item) =>item.name.toLowerCase().includes(search.toLowerCase())),};
You have seen that React Table does not offer a native plugin for a search feature. However, since you can just pass a searched list from the outside to the table and search it from the outside as well, you have all the options at your hands.
Last but not least, if you want to see how a table filter works instead, head over to my React Table with Filter tutorial.