React table custom cell

React table custom cell DEFAULT

Building a React table component with react-table

If you’re building internal tools – admin panels, dashboards, CRMs, you name it – chances are you’re thinking about how to build a table component to display, edit, and manipulate data. And if you’re working in React, you (thankfully) don’t need to build it from scratch: the react-table library gives you Hooks to get tables up and running quickly.

By the end of this tutorial, you’ll know how to:

  • Build a simple table with React and modify data, columns, and headers
  • Give your table a custom UI by passing CSS into each component using or piggybacking off a React component library.
  • Extend your table with more features like sorting, filtering, and pagination.

Learning all of these things yourself can be complicated. Thankfully, the react-table library is killer (and we made you this guide to help).

Intro: react-table


React-table is an open-source library specifically for building (you guessed it) tables in React. The library has over 11.5k stars on GitHub and is used by tons of big-name tech companies, like Google, Apple, and Microsoft. Plus, we like it so much here at Retool that we sponsor it.

We like react-table because it’s easy to set up, customize, and extend. The library covers the basics of a useful table — sorting, filtering, and pagination — but also goes much deeper with advanced features like:

  • Grouping
  • Expanded State
  • Custom Plugin Hooks

It should be noted that react-table is a “headless” UI library. The library doesn’t actually render a user interface. While this may sound strange, it was designed this way to give you more control over the look and feel of the react-table component while keeping the package size small. Don’t worry, adding UI is easy, and we will cover that later on.

Since we’re all about internal tools, let’s imagine that we are building a table to display order information for customer service reps. Our table will need to display customer info (name and address) and order info (order number and date) for each customer’s purchase.

When you’ve finished working through this tutorial, you will have five versions of a table built with react-table: simple, styled, sortable, filterable, and paged. Below is the final, paged version we’re aiming for.

Retool-React-Table-Pagination

It could look better, but that’s what CSS is for!

Build a simple table with react-table


First, we’ll build a basic table to display data, no styling or extra features. Our customer support reps need an easy way to view order information for each customer. Our simple table will have two top-level headers: User Info and Order Info. Under User Info, we need two secondary headers to display each customer’s Name and Address. Under Order Info, we need two more secondary headers to display the Date that the order was made and the Order Number.

In this section, we’ll build a table with four columns split into two groups. We’ll break down how to define the shape of column objects and data, parse header groups, and fill out our rows and cells. At the end, expect to see something like this:

Retool-React-Table
Note that we did add a tiny bit of extra styling to this section, so the table has lines.

Taking care of housekeeping basics first, you’ll need to install react-table by using a package manager (Yarn or npm) and import the library into your React app:

Then, once react-table is installed and imported, it’s time to define our data and columns by way of the Hook. React-table leverages Hooks, which are a fairly new addition to React (as of version 16.8). If you’re not familiar with React Hooks, we recommend taking a look at React’s Hooks at a Glance documentation.

The most important Hook for our table is . We’ll pass two arguments to :

  1. data = table data defined with the Hook (data must be memo-ized before it can be passed to to cut down on calculation time by preventing unchanged data from being rerun)
  1. columns = column definitions defined with the Hook (column defs must be memoized before they can be passed to )

Take a second to look at the relationship between data and columns. The in columns is the “key” in the data object. This is important to be able to access the right data for each column once we use .

Once we have defined data and columns, it’s time to implement our Hook. Pass data and columns into , which will return properties that we can extract to build our table UI.

Now, we’ll use these extracted properties to build out our table via familiar JSX tags – , , , , and – and then fill in our properties from .

Table

First, we need to wrap the rest of our code, and we need to pass the function in to resolve any table props.

Things start to heat up a little bit when we start to build our headers! On a high level, all we are doing is creating our header rows using the column header names that we defined above. Before we jump into the code, let’s look at the rendered table to get a better idea:

Retool_headers_groups

Each circled section in the table above is a headerGroup, which is simply an object that contains an array of headers for that row. For this table, we will have two header rows: the header circled in red is the first headerGroup, and the header circled in blue is the second headerGroup.

To get the data we need to build these headers out of headerGroups, we will be using JavaScript’s method. If you’re unfamiliar with it, take a second to read the docs.

First, we have our tag, which is simple enough. Inside of that tag, we are going to use to parse each headerGroup, creating a new row using the and passing that headerGroup’s method in.

Inside of the , we use again, but this time on the array of headers. Each header object has a property (which is the name you’ll give each header), a function, and another prop resolver function called .

For each column, we use the tag to create the column, being sure to pass that column’s prop resolver function and then use the function to access the Header.

Table Body

Similar to how we did and , we add and pass the prop resolver function in. Then, we use to iterate through rows, which is an array of Row objects. Each Row object has a cells field, which is just an array of Cell objects that contain the data for each cell in the row.

Retool-React-Table-Component-Table-Body

The orange circle shows a row, and the pink circle shows a cell.

For each row, we need to pass the row object to the function, which helps with rendering efficiently. Next, we return tags to render the row. In each , we again use to parse cells. For each cell, we create a tag, pass in the prop resolver function , and then render the cell data using the method.

Let’s put all of that together to render our table.

Using the above code, you’ll end up with a rendered table that looks like this:

Retool-Simple-React-Table-Final

Give your table a custom UI


Even if you’re building a tool that will only be used by an internal team, it’s still important for the UI to look good (or at least not terrible). Styling (at least the basics) is extra important with react-table too since no components are actually rendered as part of the library. Without any styling, you’ll end up with a table like this:

Retool-Simple-Unstyled-React-Table

You can style your react-table component by either creating custom styles or through a React component library. The final product from this section will look like this:

Retool-React-Table-Styled

Isn’t it beautiful?

Using the Prop

Styling your table with react-table is as simple as passing CSS into the prop of each component. Let’s look at the tag for styling a header row:

You can also use CSS files and CSS modules if you’d like. Check out React’s CSS docs for more info.

Using

is a nifty React library that lets you style React components with CSS directly inside of JS code (as opposed to external CSS files). Lately, it’s become a really popular way to handle component styling in React, so you might want to use it for your table.

To use , install the library and import it into your project. Create a component that uses from the library to create a with the styles for your table in CSS. Move all of your code for creating the component into its own function. Then, in your function (where your columns and data are defined), return with your rendered inside. This will apply the styles from the on to your table.

Using a React Component Library

If you don’t want to style things yourself, using a React component library is the way to go. For this example, we’re going to use the library to create a nice table with react-table.

Going off of the Cell styling example above, we simply have to import from .

This will bring all of the styling of the component in . No extra work for you!

Click here for a full sandbox version of this code.

Extend your table with more features


No table worth rendering is going to have only two columns and three rows, like our example. Most likely, you're going to have a hefty portion of columns and row upon row of data. You'll need features to allow users to sift through all that data, like sorting, filtering, and pagination.

Sorting

We want to give our customer service reps the ability to easily find what they are looking for, and sorting is a great way to accomplish that! If the reps want to see the most recent orders placed, they can sort by date from the Date column. If they want to scan through the customers alphabetically, they can sort by name in the Name column.

Sorting is accomplished by using the Hook from react-table. Be sure to add that to your import statements:

Next, you’ll need to pass into the Hook arguments:

If you want the sorting to be done by anything other than the default alphanumeric value, you’ll need to update your definition with a field. Sorting options include:

  • = Best for sorting letters and numbers (default)
  • = Best for sorting numbers between 0 and 1
  • = Best for sorting by date

For this example, we will be using the default, but if you needed to add that code, it would look like this:

Now there are two more things to do. First, pass the function into your function. The function resolves props for toggling the sort direction when the user clicks on the header.

Second, add a tag to display an arrow up, an arrow down, or nothing to the column header to indicate how that column is sorted. You can determine how the column is sorted by checking column properties and .

Retool-Styling-React-Table

Check out this code sandbox for a more advanced version of sorting using react-table.

Filtering

For the sake of simplicity, this tutorial is going to focus on how to add a text filter on the columns of our simple table. This will give our customer support reps the ability to quickly find the information they are looking for. If a customer contacts them, the rep can easily search the Names column for that customer to find their orders or search the Order Numbers column to look up a specific order.

For further examples of all the different kinds of filters (including global, which is really useful), check out this the react-table docs.

Filtering is accomplished by using the Hook from react-table. Be sure to add that to your import statements:

Next, you’ll need to pass into the Hook arguments:

Now, we are going to add the UI for the column filter into our table. If there is a filter applied to this column, we render the UI for the filter by calling the column’s method on the Filter field. Otherwise, do nothing.

But wait! We haven’t defined the UI for the filter yet. We’ll need a function to do that – for our filter function, we first want to find out how many rows are left to be filtered, so we can display that number to the user as an input placeholder. Then, we will render an for the user to type what they want to filter.

Our function receives three values from column:

  • filterValue = the current value that this column is using to filter.
    • This value is set from the table’s state filters object.
  • preFilteredRows = Array of rows passed to the column before any filtering was done.
  • setFilter = function that takes in a filterValue in order to update the filterValue of this column (in this case, it’s taking the value that the user types into the ).

Once we’ve defined our filter function, we’ll update the definition of our column object to have a field. Add this code to your Table function:

Finally, make sure to pass in with the columns and data arguments when you use :

Retool-React-Table-Filtering

The data we created for the example in this tutorial is pretty small compared to what you would see in the real world. Only six rows? Please. In reality, our customer support reps would be dealing with hundreds (maybe even thousands) of rows of customer data. To avoid long render times and ginormous pages to scroll through, we are going to add pagination to our table. This will allow react-table to only deal with rendering some rows at a time and will take some strain off the customer support reps from having to look at overwhelming amounts of data.

Pagination is accomplished by using the Hook from react-table. Be sure to add that to your import statements:

Next, you’ll need to pass into the Hook arguments, set the initial state (if you want to start the at anything other than 0 or have the bigger or smaller than 10), and extract extra properties from what it returns.

Note that as well as iterating through in as we did previously before pagination, we are going to iterate through , which is similar to except it only has the number of rows that fit on the page. If you don’t do this, you can click those buttons as much as you want — the data won’t move. Trust me.

In this example, we have a button to go to the Previous Page, a button to go to the Next Page, and an input that lets the user type a page number to jump to.

Retool-React-Table-Pagination

Check out this code sandbox for a more advanced version of pagination using .

Your Table Component with


Hopefully, this tutorial helps you understand how to create, style, and extend a table in React using . For more advanced tutorials, we recommend checking out the “Kitchen Sink” example from ’s docs. It has fully fleshed-out examples of most things that has to offer, from pagination and sorting to filtering, grouping, expandable rows, and row selection.

Sours: https://retool.com/blog/building-a-react-table-component/

Rendering custom cells the correct way

August 21, 2020 at 8:36am (Edited 1 year ago)
Greetings, I am trying to render custom cells, but I keep getting . While the React component inspector tells me they all have unique keys.
Header: "Country",
accessor: TABLEHEADERS.COUNTRY,
const { value, cell } = props;
return <TextCell {...cell.getCellProps()} className={`is-${cell.column.id}`} value={value} />
How I try to render them:
Am I doing something wrong?

September 30, 2020 at 2:24pm
2:24pm
I had the same problem. Solved it by providing key like this: return page.map((row, i) => { prepareRow(row); return ( <tbody {...getTableBodyProps()} key={i}> <tr {...row.getRowProps()}> {row.cells.map((cell) => { return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>; })} </tr> </tbody> ); });
Edited
Sours: https://spectrum.chat/react-table/general/rendering-custom-cells-the-correct-way~ea55cb63-4a7d-4d16-be94-24942e99fffd
  1. What replaced the nissan juke
  2. Oakland county delinquent tax list
  3. Fictional characters starting with p
  4. Valorant looking for team discord

Introduction to react-table component

Table makes your data looks prettier and makes it more intuitive to read. We can arrange our data in rows and columns. One such pre-built open source npm package is react-table, which is lightweight, fast and is used for making extensible grids for react.

React-table has out of the box features such as sorting, filtering, row selection, column ordering and many more which makes it unique. For more details refer to this documentation (https://react-table.tanstack.com/docs/overview).  

Before starting one must have basic knowledge about:

  1. Basics of creating SPFx solution
  2. React Fundamentals

React-table is easy to use and can be used with SPFx easily. React-table needs data in array format and columns also in array format. Columns take at minimum Header and accessor as column definitions. Here Header is the display name given to the column of the table and accessor is the key in the data (used for mapping column to the matching data).

Basics of rendering rows and columns

React-table works in very organized manner. It requires Header and accessor as column definitions. We have our main react table component which we can import in any other component and use accordingly. We must pass table data and column data in table component and other properties that we need according to our use case scenario. Table data needs to be in array format in the way shown below:

Here we are getting data and storing it in array format in a variable named “data” of type array and further we are maintaining a state to store data. Similarly like this react table needs column data also in array format as shown below:

Further data and column are passed to the react table component. Now in table component we are passing tableitems state in the data property and columns which we are importing from TableColumn.tsx file. At the bottom of this post you will find the github repo link with all the source code shown above.

Properties like _OnRowClick and _OnCellClick are not required properties, they are used according to the scenario.

After we have passed all the required properties to the table component now it will receive the properties and display the data.

Now the table component will display the “columns”as table headings and “data” as table row data.        

React-table provides the end user a large variety of customizations to add more functionality. Here we will see how to customize react-table in different manner, such as different scenarios in row customizations and column customizations.

Row customization scenarios

Conditional rendering of table data

Conditional rendering provides the capability to render data in different use case scenarios. We can make use of this capability in displaying our row data and making our table row clickable.

 We have Added a condition in the return function based on which different table data gets rendered.

Basically, in the “data” array we are setting Hyperlink property as true or false according to which data renders. After data is passed to the table component, we can access row data and check the value of the Hyperlink property.

The table without border is the one having “Hyperlink” values

The table with border doesn’t have “Hyperlink” values

Apply hyperlink to table row

We can apply hyperlink on row data to make it clickable, we have passed a hyperlink parameter in our data that has value true or false which specifies which table row will have hyperlink in it.

As we have seen above how we have passed Hyperlink property as true or false based on which conditional rendering of table data is happening. If hyperlink property is true, then we will display table data in which table row has Link tag and will redirect to the specific link.

If we click on any of the row it will take you to the specific link provided in the link tag.

After clicking on the row it will take you to

Making a single cell clickable in a row

We can make a single cell clickable in row by applying an onClick event on the data of that cell and make it an anonymous function for passing cell value. In the “showDescriptionData” function are getting “Description” as a parameter and passing it in “alert” function.

NOTE: If we are using the “Cell” property then, return function should not be empty, otherwise column will not display any value.

After we click on the description cell it will display an alert on the webpage showing the description data.

Maintaining Pagination with react-table component

Pagination is used for breakdown of large data and displaying it in a particular manner with a specific page size. In our solution we have used reactstrap pagination because it comes with inbuilt functionality and is very easy to use. For more details refer to this document (https://reactstrap.github.io/components/pagination/).

For using pagination in our solution, we have made two separate react-table component, react-table without pagination and react-table with pagination (providing page size). This gives us freedom whether we want to use pagination or not because sometimes there are scenarios where one page requires a table that has pagination in it while other page requires a table without pagination, so this logic makes our work easy.

We have two buttons that displays specific table based on conditional rendering. We have maintained two state showTable and showPageTable to manage our conditional rendering in table.

When we click on “Table Without Pagination” button it sets showTable state to true and showPageTable to false and similarly if we click on “Table With Pagination” button it sets showPageTable to true and showTable to false.

Table Without Pagination” is the original react-table component where all the table data is displayed, we have used its instance in “Table With Pagination” component and included reactstrap pagination separately. We have calcuated total number of pages and breaked the data according to the page size.

We have passed pageSize property while calling the component (as shown above) which specifies how many items are to be shown in table in one page. We have set currentpage to 1 by default and after that we will calculate index of last item which will be currentpage*pagesize (suppose currentpage is 1 and pagesize is 4 so index of last item will be 4), now we will calculate index of first item which will be index of last item-pagesize (index of last item is 4 and pagesize is 4 so it will be 0). Now we will split our data on the basis of index of first and last item (we have used data.slice() method for this, now it will split our data from 0 to 4th index i.e, data(0,4). After that we have calculated the totalPages by dividing data.length and pageSize (we have used Math.ceil() function for this, suppose data.length is 14 and pagesize is 4 it will divide 14 by 4 which will give 3.5. So Math.Ceil() will convert it to 4 which are the number of pages). pageCount is an array which will display the page number under the table.

After we have done all the calcultions, we can add react-table component and pagination separately.

We have passed currentData in the data property and columns in the column property and _onRowClick and _onCellClick  are null as these are not required in this scenario.

Now in pagination part we have used reactstrap pagination, for displaying page number we have used pageCount array. We have applied map() function on pageCount array and each item of pageCount array will become a pagination item. We have used hadlePageClick() event for navigation between pages, which will set currentpage to the page number which is clicked.

Column customization scenarios

Adding image in row

We can apply images in row from table columns by creating a separate column.

Here Header is returning null as we are not displaying the column name, we are receiving the row data in the cell which we are storing in data variable as row.original, each table item has its status defined in the data according to which we are applying conditions to apply specific image to its status type.

Note: I have used images from document library which is stored in SharePoint site. You can use image from your source.

Adding Dropdown Modals in row

Modals in table row can be added with the help of table columns. We can create a separate column for this functionality. We will use reactstrap dropdown to display the modal items. For more detailed information on reactstrap dropdown you can refer to this link( https://reactstrap.github.io/components/dropdowns/).

Header is returning null because we are not displaying column name. We are maintaining two dropdown state as open and close modals. We have used an ellipses icon in dropdown. After clicking on ellipses icon, reactstrap modal dropdown opens and displays the button “Display Row Data”.

dropdownOpen” state is maintained to open and close the ellipses icon. After we click on “Display Row Data” button “showrowdata” function sets “DisplayData” to not equal to “displaydata” (which means if it is true it will set to false and vice versa). “modal” state is maintained to open and close modal.

After clicking on ellipses icon “Display Row Data” button appears, further on clicking on this button reactstrap modal appears displaying row data.

This is how our modal looks like.

Inbuilt configuration options

Applying filters and Column sorting

Table sorting is very useful feature, and it arranges data in good manner. In react-table sorting can be applied directly in the header, it is an inbuilt configuration provided by react-table.

Table filtering is also an inbuilt configuration provided by react-table and is used for searching data in the table. This scenario has not been covered in the blog nor in our code. For more detailed information refer to this link (https://react-table.tanstack.com/docs/examples/filtering).   

We have seen various customizations can be done with react-table under different scenarios. We also saw specific use cases which can help you customize react-table according to your requirements.

You can view the full code at GitHub: https://github.com/penthara/Customization-in-react-table-in-SPFx-solution

Written By-  Divyam Garg

(Software Developer Trainee)

Written By-  Divyam Garg

(Software Developer Intern)

Jasjit

Peer Reviewed By-  Jasjit Chopra

(CEO)

Peer Reviewed By-  Jasjit Chopra

(CEO)

Sanika

Graphics Designed By- Sanika Sanaye

(Creative Design Director)

Graphics Designed By- Sanika Sanaye

(Creative Graphic Designer Trainee)

Sours: https://www.penthara.com/exploring-advanced-customizations-of-react-table-component-within-spfx-solution/
Searching/filtering a Datatable in [React] (React Hooks Api, React Datatables, JavaScript Fetch API)

is the root hook for React Table. To use it, pass it with an options object with at least a and value, followed by any React Table compatible hooks you want to use.

Table Options

The following options are supported via the main options object passed to

    • Required
    • Must be memoized
    • The core columns configuration object for the entire table.
    • Supports nested arrays via the column's key, eg.
    • Required
    • Must be memoized
    • The data array that you want to display on the table.
    • Optional
    • The initial state object for the table.
    • Upon table initialization, this object is merged over the table's object (eg. ) that React Table and its hooks use to register default state to produce the final initial state object passed to the hook internally.
    • Optional
    • The initial state object for hidden columns
    • If a column's ID is contained in this array, it will be hidden
    • To update , pass a new array into which is supplied by . Changing directly won't cause the table to add the hidden columns back.
    • Defaults to
    • When , the state will automatically reset if any of the following conditions are met:
    • To disable, set to
    • Optional
    • With every action that is dispatched to the table's internal instance, this reducer is called and is allowed to modify the final state object for updating.
    • It is passed the , , and and is expected to either return the or a modified version of the
    • May also be used to "control" the state of the table, by overriding certain pieces of state regardless of the action.
    • Optional
    • If you need to control part of the table state, this is the place to do it.
    • This function is run on every single render, just like a hook and allows you to alter the final state of the table if necessary.
    • You can use hooks inside of this function, but most of the time, we just suggest using to memoize your state overrides.
    • See the FAQ "How can I manually control the table state?" for a an example.
    • Optional
    • Defaults to
    • The default column object for every column passed to React Table.
    • Column-specific properties will override the properties in this object, eg.
    • This is particularly useful for adding global column properties. For instance, when using the plugin hook, add a default renderer for every column, eg.
    • Optional
    • Must be memoized
    • Defaults to
    • Use this function to change how React Table detects subrows. You could even use this function to generate sub rows if you want.
    • By default, it will attempt to return the property on the row, or an empty array if that is not found.
    • Use this function to change how React Table detects unique rows and also how it constructs each row's underlying property.
    • Optional
    • Must be memoized
    • Defaults to

Column Options

The following options are supported on any column object you can pass to .

    • Required
    • This string/function is used to build the data model for your column.
    • The data returned by an accessor should be primitive and sortable.
    • If a string is passed, the column's value will be looked up on the original row via that key, eg. If your column's accessor is then its value would be read from . You can also specify deeply nested values with accessors like or even
    • If a function is passed, the column's value will be looked up on the original row using this accessor function, eg. If your column's accessor is , then its value would be determined by passing the row to this function and using the resulting value.
    • Technically speaking, this field isn't required if you have a unique for a column. This is used for things like expander or row selection columns. Warning: Only omit if you really know what you're doing.
    • Required if is a function
    • This is the unique ID for the column. It is used by reference in things like sorting, grouping, filtering etc.
    • If a string accessor is used, it defaults as the column ID, but can be overridden if necessary.
    • Optional
    • A nested array of columns.
    • If defined, the column will act as a header group. Columns can be recursively nested as much as needed.
    • Optional
    • Defaults to
    • Receives the table instance and column model as props
    • Must either be a string or return valid JSX
    • If a function/component is passed, it will be used for formatting the header value, eg. You can use a function to dynamically format the header using any table or column state.
    • Optional
    • Defaults to
    • Receives the table instance and column model as props
    • Must either be a string or return valid JSX
    • If a function/component is passed, it will be used for formatting the footer value, eg. You can use a function to dynamically format the footer using any table or column state.
    • Optional
    • Defaults to
    • Receives the table instance and cell model as props
    • Must return valid JSX
    • This function (or component) is primarily used for formatting the column value, eg. If your column accessor returns a date object, you can use a function to format that date to a readable format.
    • Optional
    • Defaults to
    • Specifies the width for the column (when using non-table-element layouts)
    • Optional
    • Defaults to
    • Specifies the minimum width for the column (when using non-table-element layouts)
    • Specifically useful when using plugin hooks that allow the user to resize column widths
    • Optional
    • Defaults to
    • Specifies the maximum width for the column (when using non-table-element layouts)
    • Specifically useful when using plugin hooks that allow the user to resize column widths

Instance Properties

The following properties are available on the table instance returned from

    • Memoized - This object reference will not change unless the internal table state is modified.
    • This is the final state object of the table, which is the product of the , internal table reducer and (optionally) a custom supplied by the user.
    • A nested array of final column objects, similar in structure to the original columns configuration option.
    • See Column Properties for more information
    • A flat array of all visible column objects derived from .
    • See Column Properties for more information
    • An array of normalized header groups, each containing a flattened array of final column objects for that row.
    • Some of these headers may be materialized as placeholders
    • See HeaderGroup Properties for more information
    • An array of normalized header groups, but in reverse order, each containing a flattened array of final column objects for that row.
    • Some of these headers may be materialized as placeholders
    • See HeaderGroup Properties for more information
    • A nested array of final header objects, similar in structure to the original columns configuration option, but rebuilt for ordering
    • Each contains the headers that are displayed underneath it.
    • Some of these headers may be materialized as placeholders
    • See Column Properties for more information
    • A flat array of final header objects found in each header group.
    • Some of these headers may be materialized as placeholders
    • See Column Properties for more information
    • An array of materialized row objects from the original array and passed into the table options
    • See Row Properties for more information
    • Required
    • This function is used to resolve any props needed for your table wrapper.
    • Custom props may be passed. NOTE: Custom props will override built-in table props, so be careful!
    • Required
    • This function is used to resolve any props needed for your table body wrapper.
    • Custom props may be passed. NOTE: Custom props will override built-in table body props, so be careful!
    • Required
    • This function is responsible for lazily preparing a row for rendering. Any row that you intend to render in your table needs to be passed to this function before every render.
    • Why? Since table data could potentially be very large, it can become very expensive to compute all of the necessary state for every row to be rendered regardless if it actually is rendered or not (for example if you are paginating or virtualizing the rows, you may only have a few rows visible at any given moment). This function allows only the rows you intend to display to be computed and prepped with the correct state.
    • An array of all rows, including subRows which have been flattened into the order in which they were detected (depth first)
    • This can be helpful in calculating total row counts that must include subRows
    • This is the total width of all visible columns (only available when using non-table-element layouts)
    • This function can be used to toggle or set a column's hidden state
    • Passing a is optional. If passed, the hidden state will be set to that Boolean value.
    • If a is not passed, the visibility for this column will be toggled.
    • This function can be used to set the state for the entire table.
    • If a value is passed, will be set to that value
    • If a function is passed, it will received the previous value and will be expected to return the new value.
    • This function can be used to toggle or set the visibility for all columns to or
    • If a value is not passed, the visibility for all columns will be toggled back and forth from to
    • If is passed, all columns will be hidden
    • If a is passed, all columns will be visible
    • This function can be used to retrieve all necessary props to be placed on an component that will control the visibility of all columns

The following additional properties are available on every object returned by the table instance.

    • Required
    • The columns in this header group.
    • Required
    • This function is used to resolve any props needed for this header group's row.
    • You can use the hook to extend its functionality.
    • Custom props may be passed. NOTE: Custom props will override built-in table props, so be careful!
    • Required
    • This function is used to resolve any props needed for this header group's footer row.
    • You can use the hook to extend its functionality.
    • Custom props may be passed. NOTE: Custom props will override built-in table props, so be careful!

Column Properties

The following properties are available on every object returned by the table instance.

    • The resolved column ID from either the column's or the column's hard-coded property
    • Whether the column should be currently visible or not.
    • Columns that are not visible are still used for sorting, filtering, etc.
    • This function is used to render content with the added context of a column.
    • The entire table will be passed to the renderer with the addition of a property, containing a reference to the column
    • If is a string, will render using the renderer. React Table ships with default and renderers. Other renderers like and are available via plugin hooks.
    • If a function or component is passed instead of a string, it will be be passed the table instance and column model as props and is expected to return any valid JSX.
    • This is the total width in pixels of all columns to the left of this column
    • Specifically useful when using plugin hooks that allow the user to resize column widths
    • This is the total width in pixels for this column (if it is a leaf-column) or or all of its sub-columns (if it is a column group)
    • Specifically useful when using plugin hooks that allow the user to resize column widths
    • Required
    • This function is used to resolve any props needed for this column's header cell.
    • You can use the hook to extend its functionality.
    • Custom props may be passed. NOTE: Custom props will override built-in table props, so be careful!
    • Required
    • This function is used to resolve any props needed for this column's footer cell.
    • You can use the hook to extend its functionality.
    • Custom props may be passed. NOTE: Custom props will override built-in table props, so be careful!
    • This function can be used to hide or show this column.
    • If no value is passed, the visibility of this column will be toggled.
    • Optionally pass a value to set the visible.
    • This function can be used to retrieve all necessary props to be placed on an component that will control the visibility of this column.

Row Properties

The following additional properties are available on every object returned by the table instance.

    • An array of visible objects containing properties and functions specific to the row and column it belongs to.
    • These cells are normally intended for display
    • See Cell Properties for more information
    • An array of all objects containing properties and functions specific to the row and column it belongs to.
    • Not every cell contained here is guaranteed that it should be displayed and is made available here for convenience and advanced templating purposes.
    • See Cell Properties for more information
    • A map of this row's resolved values by columnId, eg.
    • Required
    • This function is used to resolve any props needed for this row.
    • You can use the hook to extend its functionality.
    • Custom props may be passed. NOTE: Custom props will override built-in table props, so be careful!
    • The index of the original row in the array that was passed to . If this row is a subRow, it is the original index within the parent row's subRows array
    • The original row object from the array that was used to materialize this row.
    • If subRows were detect on the original data object, this will be an array of those materialized row objects.
    • The current state of the row. It's lifespan is attached to that of the original array. When the raw is changed, this state value is reset to the row's initial value (using the option).
    • Can be updated via or the row's function.

Cell Properties

The following additional properties are available on every object returned in an array of on every row object.

    • The corresponding column object for this cell
    • The corresponding row object for this cell
    • The resolved value for this cell.
    • By default, this value is displayed on the table via the default renderer. To override the way a cell displays override the Cell property of the column object.
    • Required
    • This function is used to resolve any props needed for this cell.
    • You can use the hook to extend its functionality.
    • Custom props may be passed. NOTE: Custom props will override built-in table props, so be careful!
    • Required
    • This function is used to render content with the added context of a cell.
    • The entire table will be passed to the renderer with the addition of , and properties, containing a reference to each respective item.
    • If is a string, will render using the renderer. React Table ships with a default renderer. Other renderers like are available via hooks like .
    • If a function or component is passed instead of a string, it will be be passed the table instance and cell model as props and is expected to return any valid JSX.

Example

← PrevOverviewNext →useFilters

Edit this page on GitHub

Was this page helpful?

Sours: https://react-table.tanstack.com/docs/api/useTable

Cell custom react table

React Table 7 - Hooks Based Library

React Table 7 - Hooks Approach to Creating Tables in React

React table v7 is a lightweight (5-14kb), headless (100% customizable), and fully controllable tool for building fast and extendable data grids for React. The Library was created by Tanner Linsley, and it is clearly documented on Github.

Differences and Migration from v6 to v7

It’s true that there is a clear and significant difference between the two versions. Version 6 of React Table requires importing the main component and ready-made CSS styles. Both the functionality and the appearance of the UI are controlled by passing the appropriate props to the main component. The latest version of React Table (v7) is headless, which means that it doesn’t provide or support any UI elements. The responsibility for providing and rendering table markup rests solely with us. This gives us the opportunity to build a unique look and feel for our table. React Table v7 uses React Hooks both internally and externally for almost everything. It’s up to us to decide how to build and what functionalities to use. The provided collection of custom React Hooks brings us one step closer to achieving our goal.

You may have already used React Table v6 in the past. This version enjoys great popularity; that said, as the creator himself has pointed out, it could no longer be maintained. Perhaps this very fact or the architecture based on hooks (and thus its performance), will prompt you to switch to a newer version.

Starting with React Table 7

The best approach for starting with React Table v7 is learning by building a simple table, and then expanding it with new functionalities.

In this article, we start by building a simple table from scratch. With each subsequent step, we equip our table with new features such as sorting, filtering, sub-components, pagination and we add bootstrap styling as well.

Below is a photo of the final version we will build together, step by step. You can play with the table here: Demo.

photo-1



At the end of each step, there’s a link to the current code. Let’s begin then!

Project Setup

We start by creating a new React project using

The next step is to install the library

Prepare Data

We use radnomuser API as data to fill the table

Our first task is to fetch 100 user contacts. We’ll do this with native JavaScript fetch and the React useEffect hook.

Each contact is a plain JS object that consists of information such as name, location, gender, contact details and picture.

Define Columns

Once we have our data all ready, the next step is to define the column structure (an array of objects that consists of header - column name and accessor - key in data). For optimization purposes, we wrap our columns in the React useMemo hook.


data-1

Table Rendering - useTable Hook

The first and most important hook we’ll use is useTable

useTable requires an object with two properties: data (our contacts) and columns, which we have previously defined. The hook returns properties that we need to destructre, and we need those to build our table. Their purpose and place are explained in the code below.

We start building our Table in a separate component This is the basic version of the table, which will be the base for implementing additional functionalities. Please note how our destructured properties from the useTable hook are used.

All of the code we have written so far, can be found here. Don’t forget to star the repo if you find it useful!

Add Bootstrap Table Style

As we mentioned earlier, version 7 of React Table does not support any UI view. The style of the table is up to us. In our example, we utilize the Bootstrap appearance for this purpose. To do this, we need to install two packages.

The first thing to do is to import bootstrap styles. A bootstrap container is also added in order to position the table into the center.

After importing bootstrap styles, all we need to do is replace the HTML table with the Bootstrap Table component.

The code with added bootstrap is available here

Custom Cell

React Table 7 allows you to define a custom look for each cell. We can do this in the definition for a given column. As far as Table Cell goes, we can render any React Component.

In our example we are going to create a new column - Hemisphere, which we use to render the hemisphere sign based on user coordinates. In , we will destructure the latitude and longitude values to determine the user’s hemisphere.

Next, we render the respective sign.

Link to the current code. Don’t forget to star the repo if you find it useful!

Sorting - useSortBy Hook

sorting

React Table 7 allows us to easily create sorting for our table. To create sorting, we will need another hook from the React Table hooks collection - useSortBy

We pass the useSortBy hook as a parameter to our main useTable hook. React Table automatically handles sorting in ascending/descending order.

All we need to do is to make a minor change in the way we render column headers. In the column header definition, we invoke the function on a column - which returns an onClick event responsible for changing the sorting direction. We have included - a helper function which returns the sort indicator based on sorting state (ascending/descending/no sorting). Code below.

With this implementation, we can do sorting on each column by default. If we want to disable sorting in a particular column, we need to set the property to true in the column definition.

You can find the code for the table with sorting here. Again, if you haven’t done it already - don’t forget to star the repo if you find it useful!

Filtering - useFilters Hook

filtering

The next feature that we will add to our table is column filtering. With the useFilters hook, we can do it an easy and accessible way. Like before, we need to pass the useFilters hook as a parameter to our main useTable hook. useFilters must be placed before useSortBy, otherwise React Table 7 will inform us about that fact in the console. ()

After connecting the useFilters hook, the next step will be to modify the way of rendering for our . We add the component that will display the view for our filters. On top of that, we wrap the rest of the header cell in so that clicking on our filter does not trigger sorting in a column.

Let’s create a new file , in which we are going to write views for our filters :)

- a universal component for rendering a filter view

Now, we are going to write our two filters, which we want to use in our table. The first filter - will render Text Input, which filters based on the entered text (the text filtering functionality is provided by default by the React Table). The second of them, , renders Select Input which allows to choose from the available options.

How to use our filters?

  1. - is passed as a default filter for columns to the useTable hook, which means that each of our column uses this filter until it is turned off or another filter is attached.
  1. - adding the “Filter” prop in Column Definition (overrides the default filter).

If you don’t want to display any filter in a column, simply add this line of code in for that column:

The code for the table with added filters is available here.

Sub Components - useExpanded Hook

Sub Components

The first step is to import the useExpanded hook from React Table and join it with our useTable. Next a prop from useTable is destructured, to make sure that our Sub Component will take 100% of the table width.

To display the Sub-Component, we need to modify the rendering for a table body We use the value to determine whether we want to display the Sub-Component.

We use the file to write the function as well as the column definition with emoji indicating whether our row is open or not.

The function, renders a simple Bootstrap Card with contact details. We need to pass it as a prop to .

After implementing the above steps, you should have a working sub-components functionality after clicking the right emoji.

The code can be found here.

pagination

The last hook we are going to implement is usePagination. As always, we need to add usePagination to our useTable. This hook requires destructuring of several additional props that we need to build our pagination. In addition, we define initialState in which we specify how many rows we want to display () and from which page we start displaying ().

Instead of using , we use (which only keeps rows for an active page),

Let’s create two helper functions that can handle changing pages both in Text Input and Select Input

Then, below definition we create our pagination. This is only an example - you can build and style it in any way you want!

If you have implemented the above steps, you should now have a working pagination for your table. usePagination is the last hook we have used to build our table.

You can find the whole code here.

Conclusions

Voilà! We have a ready table that is equipped with some interesting features. The table made in this article is merely an introduction to building more advanced, custom tables with the help of React Table 7!

In fact, there is a whole another spectrum of functionalities that we can get with React Table 7. It’s up to us how we will construct our table. For more information and examples please refer to this great documentation.


Bartek Bajda

Written by Bartek Bajda.

Sours: https://thewidlarzgroup.com/react-table-7/
React Tables From Zero to Hero

Some of our employees had to have time to inspect the kindergarten in the nearest village and sat down on the transport, saying goodbye, went. There, and the three of us stayed. The dinner was headed by the director of the orphanage, his deputy and head physician and the three of us. Lunch took place in one of the buildings adjacent to the common building, in which, to my surprise, in addition to the comfortable offices of the authorities, there.

Similar news:

Having learned that they were taking me as a home dog, I didnt really get over it, reasonably assuming that I had nothing to count on the. Best option. And I was right. A good family husband named, damn named Peter, calm and imperturbable dude, athletic build. His wife - Zina, very much a wife.



479 480 481 482 483