logo

Education

Mastering React Table Style: Your Comprehensive Guide

Authore Name
Ravi Sojitra

Engineering Manager

Last updated on Apr 30, 2024

Welcome to the world of React Table styling, where the creation of dynamic and responsive tables in your React app becomes not just a necessity but an art. React tables allow you to display and manipulate large data sets quickly, but how do you begin styling these tables to make them functional and visually appealing?

Let's dive in!

Understanding the Basics of Table Creation in React

Creating a basic table in React is straightforward, thanks to the React table library. You can set up a simple table with just a few lines of code.

But what exactly is a React table library?

It's a collection of React components designed to build and style tables efficiently, offering features like sorting, filtering, pagination, and more.

1import React from 'react'; 2import { useTable } from 'react-table'; 3 4function App() { 5 const data = React.useMemo(() => [{ col1: 'Hello', col2: 'World' }], []); 6 const columns = React.useMemo(() => [ 7 { Header: 'Column 1', accessor: 'col1' }, // This is a column object 8 { Header: 'Column 2', accessor: 'col2' }, 9 ], []); 10 11 const tableInstance = useTable({ columns, data }); 12 13 const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } = tableInstance; 14 15 return ( 16 <table {...getTableProps()}> 17 <thead> 18 {headerGroups.map(headerGroup => ( 19 <tr {...headerGroup.getHeaderGroupProps()}> 20 {headerGroup.headers.map(column => ( 21 <th {...column.getHeaderProps()}>{column.render('Header')}</th> 22 ))} 23 </tr> 24 ))} 25 </thead> 26 <tbody {...getTableBodyProps()}> 27 {rows.map(row => { 28 prepareRow(row); 29 return ( 30 <tr {...row.getRowProps()}> 31 {row.cells.map(cell => ( 32 <td {...cell.getCellProps()}>{cell.render('Cell')}</td> 33 ))} 34 </tr> 35 ); 36 })} 37 </tbody> 38 </table> 39 ); 40} 41 42export default App; 43

Overview of React Table Libraries

Selecting the right React table library is crucial when enhancing your React app with tables. Among the plethora of table libraries, React Table stands out for its flexibility and customization options. However, it's not exactly a table library in the traditional sense; it's more of a hooks library that allows you to build your own React table UI with custom styles and functionalities.

React Table, especially in its latest versions, v7 and v8, offers extensive features such as custom sorting, global filters, and even the ability to create mini Google Sheets. This makes it a popular React table library among developers looking to implement advanced data grid functionalities.

Why React Table?

React Table's philosophy is simple: it provides the hooks and utilities needed to build a table UI entirely of your styling without imposing any markup or style decisions. This approach allows you to use whatever table UI or components you prefer, whether crafting a bare table or a complex data grid.

Selecting the Right React Table Library

Regarding React tables, developers have a plethora of libraries to choose from. Each library offers unique features, performance characteristics, and styling options. However, two names often appear in the discussion: React Table and Tanstack Table (formerly known as React Table v7 and v8). Let's compare these and evaluate other libraries to help you make an informed decision.

Comparing React Table v7 and v8

React Table v7 and v8, part of the Tanstack suite of libraries, are powerful tools for building and managing tables in React applications. The transition from v7 to v8 brought significant improvements and changes, especially in how tables are rendered and managed.

React Table v7 introduced a flexible hook-based architecture, enabling developers to build highly customizable tables. It supports virtual rendering, allowing for efficient rendering of large datasets. React Table v8, or Tanstack Table v8, builds upon this foundation with improved performance and additional features like automatic column resizing and better touch support, making it a compelling choice for modern web applications.

Evaluating the Best Table Libraries for React

Beyond React Table, there are other notable table libraries such as AG-Grid, Material-UI's DataGrid, and Ant Design Tables. Each comes with its own set of features:

  • AG-Grid offers enterprise-level features, including complex filtering, sorting, and a wide range of customization options. It's ideal for applications requiring advanced grid functionalities.
  • Material-UI DataGrid integrates seamlessly with Material-UI components, providing a consistent design language and simple customization through themes.
  • Ant Design Tables are part of the Ant Design system, offering rich features and an extensive set of controls, making them suitable for applications following the Ant Design guidelines.

Choosing the proper library depends on your project's requirements, the complexity of the data you're dealing with, and the level of customization needed. When deciding, consider factors like performance, documentation, community support, and the learning curve.

Building a Basic Table in React

Before advancing to more complex features and customization options, it's essential to understand how to create a simple table in React. This foundation will serve as the basis for further exploration and styling.

Step-by-Step Guide to Creating a Simple Table

Creating a basic table involves defining your data and columns and using a React table library to render the table. Here's a simple example using React Table:

1import React from 'react'; 2import { useTable } from 'react-table'; 3 4function SimpleTable() { 5 const data = React.useMemo(() => [{ name: 'John', age: 30 }, { name: 'Jane', age: 25 }], []); 6 const columns = React.useMemo(() => [ 7 { Header: 'Name', accessor: 'name' }, 8 { Header: 'Age', accessor: 'age' }, 9 ], []); 10 11 const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } = useTable({ columns, data }); 12 13 return ( 14 <table {...getTableProps()}> 15 <thead> 16 {headerGroups.map(headerGroup => ( 17 <tr {...headerGroup.getHeaderGroupProps()}> 18 {headerGroup.headers.map(column => <th {...column.getHeaderProps()}>{column.render('Header')}</th>)} 19 </tr> 20 ))} 21 </thead> 22 <tbody {...getTableBodyProps()}> 23 {rows.map(row => { 24 prepareRow(row); 25 return ( 26 <tr {...row.getRowProps()}> 27 {row.cells.map(cell => <td {...cell.getCellProps()}>{cell.render('Cell')}</td>)} 28 </tr> 29 ); 30 })} 31 </tbody> 32 </table> 33 ); 34} 35

Styling Tables Using CSS in React

Once your table is set up, styling it with CSS can enhance its appearance and improve readability. You can apply styles directly to your table components using inline styles, CSS classes, or CSS-in-JS libraries like styled components. Remember to focus on responsiveness, accessibility, and consistency with your application's design system.

1/* Example CSS for a simple table */ 2.table { 3 width: 100%; 4 border-collapse: collapse; 5} 6 7.table th, .table td { 8 border: 1px solid #ddd; 9 padding: 8px; 10 text-align: left; 11} 12 13.table thead { 14 background-color: #f2f2f2; 15} 16 17.table tr:nth-child(even) { 18 background-color: #f9f9f9; 19} 20

To apply these styles in a React app, you can include the CSS in your project's main stylesheet or define them within a CSS module for component-specific styling. Here's how you might incorporate the styles using a CSS module:

1import React from 'react'; 2import { useTable } from 'react-table'; 3import styles from './TableStyles.module.css'; // Assuming your CSS module is named TableStyles.module.css 4 5function StyledTable({ columns, data }) { 6 const tableInstance = useTable({ columns, data }); 7 8 // Destructure properties from the table instance 9 const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } = tableInstance; 10 11 return ( 12 <table {...getTableProps()} className={styles.table}> 13 <thead> 14 {headerGroups.map(headerGroup => ( 15 <tr {...headerGroup.getHeaderGroupProps()}> 16 {headerGroup.headers.map(column => ( 17 <th {...column.getHeaderProps()}>{column.render('Header')}</th> 18 ))} 19 </tr> 20 ))} 21 </thead> 22 <tbody {...getTableBodyProps()}> 23 {rows.map(row => { 24 prepareRow(row); 25 return ( 26 <tr {...row.getRowProps()}> 27 {row.cells.map(cell => ( 28 <td {...cell.getCellProps()}>{cell.render('Cell')}</td> 29 ))} 30 </tr> 31 ); 32 })} 33 </tbody> 34 </table> 35 ); 36} 37

This approach ensures that your table styles are encapsulated within the component, reducing the risk of style conflicts and promoting consistency across your application.

Advancing to React Table v7 and v8

With a solid understanding of creating and styling a bare table in React, let's explore the advanced features and differences in React Table v7 and v8. These versions bring powerful capabilities to the table (pun intended), allowing for more dynamic and interactive table data representation.

Key Features and Differences

React Table v7 introduced a hook-based architecture that revolutionized how tables are built in React. It allowed developers to construct tables using functional components and React hooks, offering greater flexibility and control over table functionality.

React Table v8, or Tanstack Table v8, further enhances this foundation with additional performance optimizations and features. One of the key improvements is the automatic handling of column resizing and better integration with virtual scrolling, making it easier to manage large datasets efficiently.

Implementing Advanced Styling in v7 vs. v8

Both versions support advanced styling options, but v8 simplifies the process of implementing custom styles and themes. With v8, you can leverage the built-in hooks and components to apply custom styles directly to your table elements, making achieving the desired look and feel more accessible.

For instance, to implement horizontal and vertical scrolling in a React Table, you might adjust your table container's CSS to include overflow properties and set fixed widths on specific columns to ensure the table behaves as expected on all screen sizes.

1/* CSS for scrolling in React Table */ 2.tableContainer { 3 overflow-x: auto; 4 display: block; 5} 6 7.fixedWidthColumn { 8 width: 150px; 9} 10

When applying these styles, it's crucial to test your table's responsiveness and ensure it remains accessible and usable across different devices and screen sizes.

Customizing Tables in ReactJS

Customization is critical to making your tables stand out and providing users with a seamless experience. React's flexibility and the power of React Table make this process both accessible and versatile.

Creating a Custom Table Component

Developing a custom table component in React involves encapsulating all the functionality and styling you need into a single, reusable component. This approach promotes code reusability and simplifies implementing tables across your application.

Let's create a custom React table component that utilizes React Table for handling data and includes custom styling for a unique appearance.

1import React from 'react'; 2import { useTable } from 'react-table'; 3import './CustomTable.css'; // Import your custom CSS here 4 5function CustomTable({ columns, data }) { 6 const { 7 getTableProps, 8 getTableBodyProps, 9 headerGroups, 10 rows, 11 prepareRow, 12 } = useTable({ 13 columns, 14 data, 15 }); 16 17 // Table structure with custom styling 18 return ( 19 <div className="table-wrapper"> 20 <table {...getTableProps()} className="custom-table"> 21 <thead> 22 {headerGroups.map(headerGroup => ( 23 <tr {...headerGroup.getHeaderGroupProps()}> 24 {headerGroup.headers.map(column => ( 25 <th {...column.getHeaderProps()} className="custom-header"> 26 {column.render('Header')} 27 </th> 28 ))} 29 </tr> 30 ))} 31 </thead> 32 <tbody {...getTableBodyProps()}> 33 {rows.map((row, i) => { 34 prepareRow(row); 35 return ( 36 <tr {...row.getRowProps()} className="custom-row"> 37 {row.cells.map(cell => { 38 return ( 39 <td {...cell.getCellProps()} className="custom-cell"> 40 {cell.render('Cell')} 41 </td> 42 ); 43 })} 44 </tr> 45 ); 46 })} 47 </tbody> 48 </table> 49 </div> 50 ); 51} 52 53export default CustomTable; 54

In this example, the CustomTable component takes columns and data as props, which React Table then uses to generate the table. The addition of custom CSS classes allows for easy styling and personalization.

Applying Custom Styles for Enhanced UX

Enhancing user experience with custom styles involves more than just making the table look good. It's about improving readability, interaction, and overall usability. Considerations like zebra striping for rows, hover effects, and responsive designs are essential.

For example, here's how you might add some of these styles to your CustomTable.css:

1.table-wrapper { 2 overflow-x: auto; 3} 4 5.custom-table { 6 width: 100%; 7 border-collapse: collapse; 8} 9 10.custom-header { 11 background-color: #004085; 12 color: white; 13 padding: 10px; 14} 15 16.custom-row:nth-child(odd) { 17 background-color: #f2f2f2; 18} 19 20.custom-row:hover { 21 background-color: #ddd; 22} 23 24.custom-cell { 25 padding: 8px; 26 border: 1px solid #ddd; 27} 28

These styles aim to improve the table's visual hierarchy, making it easier for users to navigate and interpret the data. Additionally, the responsive wrapper ensures that the table remains accessible on devices with smaller screens.

Styling Tables with Material-UI

Material-UI offers a robust set of React components that follow Material Design guidelines, including a versatile table component. Integrating Material-UI table components into your React app ensures consistency with Material Design principles and provides a quick and efficient way to create visually appealing and functional tables.

Integrating Material-UI Table Components

To begin with Material-UI tables, you first need to install Material-UI in your project, if you haven't already:

1npm install @mui/material @emotion/react @emotion/styled 2

Once installed, you can start using the Material-UI table components. Material-UI provides components such as Table, TableBody, TableCell, TableContainer, TableHead, and TableRow for building tables. Here's a basic example of a table built with Material-UI:

1import React from 'react'; 2import { Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper } from '@mui/material'; 3 4function MaterialTable({ data }) { 5 return ( 6 <TableContainer component={Paper}> 7 <Table aria-label="simple table"> 8 <TableHead> 9 <TableRow> 10 <TableCell>Name</TableCell> 11 <TableCell align="right">Age</TableCell> 12 </TableRow> 13 </TableHead> 14 <TableBody> 15 {data.map((row) => ( 16 <TableRow key={row.name}> 17 <TableCell component="th" scope="row"> 18 {row.name} 19 </TableCell> 20 <TableCell align="right">{row.age}</TableCell> 21 </TableRow> 22 ))} 23 </TableBody> 24 </Table> 25 </TableContainer> 26 ); 27} 28

This code snippet demonstrates using Material-UI components to create a simple table. The TableContainer wraps the Table and provides a Paper background, adding to the visual appeal.

Customizing Material Table Styles

Material-UI tables are highly customizable. You can override the default styles using the sx prop for quick inline styles or create custom themes for a more global approach to styling your tables and other Material-UI components.

Here's an example of customizing a Material-UI table with the sx prop:

1<TableCell sx={{ fontWeight: 'bold', backgroundColor: '#f3f3f3' }}> 2 Name 3</TableCell> 4

For more extensive customizations, consider using Material-UI's theming capabilities. You can define a custom theme and apply it to your entire application, ensuring consistency across all Material-UI components:

1import { createTheme, ThemeProvider } from '@mui/material/styles'; 2 3const theme = createTheme({ 4 components: { 5 MuiTableCell: { 6 styleOverrides: { 7 root: { 8 // Custom styles here 9 padding: '10px', 10 backgroundColor: '#eaeff1', 11 }, 12 }, 13 }, 14 }, 15}); 16 17function App() { 18 return ( 19 <ThemeProvider theme={theme}> 20 <MaterialTable data={data} /> 21 </ThemeProvider> 22 ); 23} 24

This approach gives you fine-grained control over the styling of table components, allowing you to align the table's appearance with your application's design system.

Material-UI's table components and customization capabilities are powerful for building responsive, accessible, and aesthetically pleasing tables in React applications. Whether you need a simple data table or a more complex interactive data grid, Material-UI provides the tools to create a seamless user experience.

Best Practices for React Table Styling

Creating tables in React that are both functional and aesthetically pleasing is essential, but it's also crucial to ensure they follow best practices for usability, accessibility, performance, and responsiveness. Here are some key considerations to keep in mind:

Responsive Design and Accessibility Considerations

  • Responsive Tables: Ensure your tables are responsive and adapt to different screen sizes. Techniques such as horizontal scrolling, collapsible columns, or transforming tables into card layouts on smaller screens can help maintain device usability.
  • Accessibility (A11y): Use semantic HTML for tables (<table>, <th>, <tr>, <td>) whenever possible, as it provides screen reader support out of the box. ARIA roles and properties can enhance accessibility further, especially for more complex table features.
  • Keyboard Navigation: Ensure that all interactive elements of your table can be navigated using a keyboard. This includes sorting controls, pagination, and any form elements within your table.

Performance Optimization for Large Data Sets

  • Virtualization: Consider using virtualization libraries like react-window or react-virtualized for tables displaying large datasets. These libraries render only the items in the viewport, significantly reducing the number of DOM elements created and improving performance.
  • Lazy Loading: Implement lazy loading for your data, primarily if your table supports pagination or infinite scrolling. This means only loading data as needed when the user scrolls, reducing initial load times and memory usage.
  • Memoization: Use React's useMemo hook to memoize your rows and columns to prevent unnecessary re-renders. This is particularly useful if your table includes complex cells requiring significant computation.

Styling for Improved User Experience

  • Consistent Design: Ensure your table's design is consistent with the rest of your application. Use a theme or design system for styling to maintain consistency.
  • Custom Styles: While libraries like Material-UI provide their own set of styles, don't hesitate to apply your custom styles to meet your design requirements. This might include custom row hover effects, selected row highlighting, or specific font stylings.
  • Feedback and Interaction: Provide visual feedback for interactive elements. For example, change the cursor to a pointer on clickable items, use hover effects to highlight rows, and provide clear indicators for sortable or draggable columns.

Conclusion and Further Resources

Styling tables in React goes beyond mere aesthetics. It ensures that your tables are responsive, accessible, and performant, providing a seamless experience for all users. Whether using React Table, Material-UI, or any other library, applying best practices in design, performance, and accessibility is critical to creating effective and engaging data tables.

For those looking to dive deeper into React Table styling and customization, here are some resources to explore:

  • React Table Documentation: The official React Table documentation is a great starting point for understanding the library's capabilities and features.
  • Material-UI Tables: Explore Material-UI's documentation for more on styling tables using their components.
  • Web Accessibility Tutorials: The W3C Web Accessibility Initiative offers tutorials on creating accessible tables, which can be invaluable for ensuring your tables meet accessibility standards.
  • Performance Optimization in React: Learn more about optimizing the performance of your React applications, including tables, through React's official documentation and community guides.

By following these best practices and leveraging the available resources, you can create React tables that look great and provide a robust, accessible, and enjoyable user experience.

Short on time? Speed things up with DhiWise!!

Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!

You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.

Sign up to DhiWise for free

Read More