Searching/filtering a Datatable in [React] (React Hooks Api, React Datatables, JavaScript Fetch API)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
today we're gonna build a data table using react Jas I'm also going to show you how to fetch data from a remote JSON API endpoint and finally I'm going to show you how to do both simple and complex searches on that data table my name is Mark from Deb mentor live let's get started now so I created this with create react app and then I just deleted all of the Brailler plate CSS and other things that I don't need if you don't want to do this yourself you can click the link down in the description to clone the code that will start you at this exact point it will also include all of the CSS that I've already included for the project and the first thing I like to do is just lay out where all the pieces are gonna be so we're gonna have a div for our filter and a div for our data table next we're going to import use state from react as well as use effect and this is going to allow us to have a place to store our data so the way that you state works is you give it a default value which we're going to start off with an empty array and that's going to return you a tuple the first value is a getter and the second value is a setter so we're going to call it data and set data the next piece of data that we're going to need to keep track of is our query filter so we're just going to name the getter Q and the setter set Q and this time you state is going to default to an empty string we're now going to load the data from our remote json api endpoint and to do that we're going to need to install a couple of packages the first one is called es6 promise and it provides promises via polyfill to your browser if your browser doesn't already support promises the second package is isomorphic fetch which is just like es6 promise it's a polyfill and it provides the fetch functionality to your browser if your browser doesn't already support it natively let's restart our web pack dev server with yarn start now that we've imported es6 promise and isomorphic fetch we need to require them and in the case of es6 promise called a polyfill function and now will require our isomorphic fetch package and this time we don't need to call the polyfill function it happens automatically with react hooks there's no need to use es6 classes and so all of the lifetime cycle functions that you might be used to like component will mount or component did mount are no longer needed we can actually do a component dead mount by calling u s-- effect and then the second argument to use effect is an array of dependencies with those dependencies change this function will fire again but since we're giving it an empty array it's only going to fire one time when the component initially loads the first argument to use effect is the function that you want to fire when the dependencies are triggered in our case we want the function to make a call to fetch so that we can get the data from a remote API fetch can take a number of arguments for right now we're going to leave those off and skip to the promise that returns when the response comes back from the server this is handled by a chained call to a function called then which takes a function and in our case it's just going to return the response it comes back from a server calling JSON on it to turn the HTTP response data into JSON data that's going to return another promise now our function is going to have access to the JSON data we can call set data and pass in the JSON variable that was returned from the previous promise which now gives our app component access to that JSON data which is stored in our local state let's take a look at the data that that JSON endpoint is going to return it looks like this we have a thousand records of contact data that's been generated randomly this is the URL to that endpoint and you can access this but you will need to sign up for your free account at dev mentor dot live to get your API key make sure to replace b7c five eight be with your api key in order to access this data let's open up our inspector and inside of there we can access our react dev tools under components and look at the data that has been brought in from the API and as you can see that JSON is now in our state and we have all thousand records loaded now that we have our JSON data loaded it's time to start building our data table our data table is going to take a single prop we're gonna call it data and we're gonna pass in the data variable that is stored in our hook next we're going to import our data table which we haven't created yet from dot forward slash data table which just means in the current directory of SRC we're going to have a folder called data table and that's going to contain our component inside of our data table folder we're going to create our component file as index dot JSP eight a functional component and I have a snippet that does this simply for me but we're going to import react from react and we're going to export a default function called data table that takes a single prop called data and we're going to return an HTML table since the html5 spec wants to have both a tea head and a tea body section we're gonna create those now and since you can't control cell padding and cell spacing on a table through CSS we're just going to put a couple of properties onto the HTML entity called cell padding set it to zero cell spacing set it to zero and keep in mind that properties that are taking an integer or a boolean value need to be a JavaScript expression which is why it's not unquote it's in curly braces now we're going to layout the headers for our table which are going to be the attributes for our JSON and we can generate these dynamically we'll start with a guard clause which is just going to protect us in case our data contains no rows because what we're going to be doing is looking at the first row and pulling the keys out of that row to use as our headings will do that by mapping over a columns variable which will contain the keys from the first row and each iteration is going to return a single heading which we can then wrap in a tea eh tag to create the header for our table now let's create that column this variable again using a guard clause in case our data has no rows because we're going to use object keys passing in the first row of data which is going to pull out all of the keys from the JSON to use as our headers and as you can see our table now displays a header that contains each of those keys now it's time to iterate over our data to grab each row out of that data variable and to display a table row tag for each of the rows in our JSON data next we're going to iterate over each of those columns using our map function to display a table definition tag which is going to show us each of those values in a cell for our row and since it's a JavaScript object we can just call row and then pass in the column in square bracket notation to get at that individual cell and as you can see now the values that are stored in our local statement have been converted into table rows and our data table is now displaying if you're enjoying the screencast leave a comment below there's no better way to let the YouTube algorithm know that this is content that should be shared with other people next we're going to use an input tag to store the query filter that we're going to use to filter our data table results it's going to be a controlled element which means that we're going to provide a value for the element as well as an on change handler to change the value of the element the on change is going to take a arrow function the arrow function is going to have a single parameter which is called e which represents the synthetic event that happens every time you type a character into that input box each time that value changes we're going to bind that value to our variable using the set Q setter that we got from our you state function and we're going to give it a dot target dot value which represents the value in the text box now going into the inspector we can test this code by opening up our react dev tools under the components tab and we can watch that state change as we type into the textbox now that we can get a value from the user in which to filter our data table by we can create a function called search which are going to take the rows from our data table and we're going to filter over those rows matching a column value in this case first name against our Q value which represents the users query in order to do that we're going to need to make a case insensitive so we're going to take the first name and we're going to convert it to lowercase and then we're going to call index of index of is going to try to match the two strings and it's going to return you the first character index that matches so if there is no match you get a negative one and you get a zero or positive number if there is a match though this function is going to return all the rows that match our query for the column first name by checking to see if the return value is greater than negative 1 to use our new search function all we have to do is wrap the data prop of our data table with our search function what this means is that the data that's stored in our state is going to be filtered through the search function before it's passed to the data table therefore the data table will only render the values that match our search query now that we know how to match one field in this case first name we can do the same thing with an or gate which means either the left or the right side is going to match by just replacing first name with last name then we can check that in our browser and make sure that we can filter on the last name which we can so let's repeat that same process with email and we can double check to make sure that we can filter an email and we can so let's continue through the process repeating this for each of the columns that we want to be able to filter by and then load that in the browser and just double check that the code works before we move on to the next one and I'll just speed up this process so that it takes a little bit less time to sit through now this works but you can see that it's quite tedious and there's a lot of repeated code so instead let's create a variable called columns again pulling out all of the keys from the first row and then inside of our filter on each row we can just map over those columns with a special function on a ray called sum which works like filter except filter has to basically match all of the expressions in order to return a single value whereas sum will return the value if it matches any of the expressions then using the same logic as we did before will just replace the specified column name in this case first name with the square bracket notation because we're mapping over those columns using the sum method now it's going to check each of those and if any of them return a index of greater than negative one then the row is going to match however we now get an error and the reason is is that not all of those columns are strings and if it's not a string it's not going to respond to the method to lowercase so to fix this we're going to need to call row square bracket column dot to string before we call dot to lowercase to cast that value as a string so that we can do the string check and as you can see that has removed the error now let's see if we can filter on the state and on the postal code which are two columns that we didn't specify earlier when we were typing all of the columns out and as you can see we can now filter on those columns as well now there's another bug lurking here which we can see by copying the last name as it is in the data and pasting it into our query we don't get any results back this is because we're casting one side of our equation as a to lowercase but we're not transforming the actual query to lowercase so let's do that now and again as you can see the problem has been fixed if you're ready to take your career or education to the next level remember that I do daily group and private mentorship sessions on a variety of topics like JavaScript react Ruby on Rails and a whole lot more you can find out more information at Deb mentor da live we're in the homestretch now there's only one last problem that we have to solve we might not want to check against all of the columns for our filter we might want to just check the first name and the email so let's implement that now we can do this by creating another piece of state using our u state call this time it's going to default to an array and let's just put first name and last name in there as the default so without doing anything else it'll search on the first name and the last name column now to make our search function not search all the columns but only the specified columns all we have to do is replace the variable columns on line 22 with our search columns variable we also don't need line 20 anymore at least inside of the search function however we will need it down in the render function when we add the check boxes so I'm going to move it now and I'm going to change the variable rows to the variable data since we're not passing in the variable rows to our render function and now we can see we can search for the first name and the last name but City no longer works next let's give the user the ability to check the columns that they want to include in the search and we can do that by iterating over our columns variable and for each iteration right now we can just print out the label of the column name so we can see that in the browser now let's add in our check boxes using an input with the type of check box and these are controlled components so we're going to set the value of checked to the boolean return of search columns dot includes and we'll pass in our column name since search columns is defaulting to first name and last name being checked we can see that those values are now checked we're going to set up our unchanged handler and the first thing that we're going to do is find out if the check box was previously checked and we can do that by setting a constant called checked to the value of search columns that includes column just like we did above now we're going to update our search columns based on what was just changed and this gets a little bit complicated just try to remember that whatever returns from the ternary we're about to create is going to be the new values stored in search columns now these setters that come from you state have two different ways that you can call them you can either just give them new values in which case the new values will be the new value in the getter or you can use an arrow function which is what we're going to do here the arrow function always gives you the previous state so if the item was previously checked we can just remove it from the search columns and if the item was previously unchecked we can add it to the search columns and we're going to do that using a ternary the first half of the ternary is going to remove the just unchecked column from our search columns and we're going to do that with a call to filter on the previous values keeping all of the values that don't match the current column second half of the ternary is going to add the column that we just checked to the list of search columns and we can do that by just returning a new array where we D structure the old array items into the new array and then append the current column to that array this allows us to update our search columns in an immutable fashion now let's check our work using the inspector and we're going to go to the components tab from react dev tools and we're going to look at the piece of state that contains the search columns currently has first name and last name but watch what happens when we check an additional column and then uncheck a column as you can see when we check a new check box it goes into our list of search columns and if you uncheck it it leaves the search columns so now we can check a different field and we can type in a search query and test to make sure it works let's do that now and that's it for this episode you can see that we built a data table we fed data into it from a remote API and we allow the user to select which columns and what text they want to filter the data set by thanks for watching today's screencast I hope you learned something if you liked it leave us a comment below and hit that like button and I'll see you next week
Info
Channel: devmentorlive
Views: 94,937
Rating: undefined out of 5
Keywords: react js datatables, become a programmer, react tutorial, react for beginners, learn to code, filtering a Datatable in React, write codes, ReactJS Fetch Api, reactjs tutorial, search and sort in reactjs, reactjs hooks, JavaScript, web development, React, javascript, technology, filter react, React Hooks Api, software, ReactJS Hooks Api, build web pages, search in reactjs, ReactJS, react hooks, software development, React Fetch Api, es6, search a datatable in react
Id: d1r0aK5awWk
Channel Id: undefined
Length: 19min 39sec (1179 seconds)
Published: Mon Jul 06 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.