Home >Web Front-end >JS Tutorial >How to Create a Sortable and Filterable Table in React
This article demonstrates building a dynamic, sortable, and filterable table component in React using Vite. Let's streamline the explanation and improve clarity.
Key Features:
useState
hook to manage table data, enabling efficient sorting and filtering.Building the Table:
This tutorial assumes familiarity with HTML, CSS, JavaScript, and basic React concepts. We'll use TypeScript for type safety, but the core logic remains adaptable to JavaScript.
Project Setup: Create a new React project using Vite:
<code class="language-bash">npm create vite@latest my-react-table -- --template react-ts</code>
Component Structure: Organize your project with the following structure:
<code>src ├── components │ └── Table │ ├── index.ts │ ├── table.css │ └── Table.tsx └── App.tsx</code>
Mock Data: Generate sample data using a JSON generator (e.g., https://www.php.cn/link/8a1df180ea2c0d298aa1d739fe720a0c). Save this data in src/data.ts
.
Component Implementation (Table.tsx
):
The core component dynamically renders the table based on the provided data. It includes functions for formatting boolean values and capitalizing headers. The styling is handled in table.css
.
Adding Controls: Enhance the component with input fields for filtering and a dropdown for selecting the sorting column. A button toggles the sort order (ascending/descending).
Filtering Logic: The filter function dynamically updates the displayed rows based on the input value. It converts data to lowercase for case-insensitive searching.
Sorting Logic: The sorting function uses the selected column and sort order to arrange the data.
Overfiltering Handling: Display a message when no results match the filter criteria.
Final Result:
The complete source code is available on GitHub (link to be provided). This tutorial provides a concise and efficient approach to creating powerful and user-friendly table components in React.
The above is the detailed content of How to Create a Sortable and Filterable Table in React. For more information, please follow other related articles on the PHP Chinese website!