Back to cookbook

ChatGPT Prompt to Build a React Data Table With Sorting, Filtering, and Pagination

14 views Published

Make this prompt yours

Share

This ChatGPT prompt is for frontend developers who need a working React data table component — the kind with sortable columns, a search/filter input, and pagination controls — without manually wiring up the state logic from scratch every time. It's built for anyone who has typed "build me a React table" into a chat window and gotten back a bare <table> with no interactivity, then had to ask three follow-up questions to get sorting and pagination added.

The prompt works by specifying the component's props, state shape, and interaction behavior up front: what columns are sortable, how filtering should match (exact, partial, case-insensitive), and how many rows per page. Giving the model this structure before it writes any code means you get a complete, working component on the first pass instead of a skeleton you have to extend across several more turns.

Because data tables tend to accumulate edge cases fast — empty datasets, a single row, filtered results that return nothing — it's worth running the generated component's prompt through Prompt Debugger before you rely on it, so those states are specified rather than left to the model's improvisation.

Prompt template

Make this prompt yours

prompt-template
248 tokens
ROLE: You are a senior frontend engineer who writes clean, accessible React components. CONTEXT: I need a React component called [COMPONENT_NAME] that displays a data table for the following data shape: [DESCRIBE_DATA_SHAPE_E.G._ARRAY_OF_OBJECTS_WITH_FIELDS_AND_TYPES] REQUIREMENTS: - Columns: [LIST_COLUMN_NAMES_AND_WHICH_ARE_SORTABLE] - Sorting: clicking a sortable column header toggles ascending/descending order, with a visible indicator of current sort state - Filtering: a single search input that filters rows by [SPECIFY_WHICH_FIELDS_TO_MATCH], case-insensitive - Pagination: [NUMBER] rows per page, with previous/next controls and a current page indicator - Empty states: show a clear message when the data array is empty, and a separate message when a filter returns no results - Accessibility: sortable headers must be keyboard-operable and expose their sort state to screen readers - Styling approach: [SPECIFY_E.G._TAILWIND_CLASSES_OR_PLAIN_CSS_MODULES] OUTPUT FORMAT: Return the complete component code in a single code block, followed by a short list of any assumptions you made about data or behavior that I didn't specify.

Want it sharper? Optimize this prompt with Prompt Optimizer, check it with the Prompt Debugger or shorten it with the Token Optimizer.

Example input

example-input
256 tokens
ROLE: You are a senior frontend engineer who writes clean, accessible React components. CONTEXT: I need a React component called CustomerTable that displays a data table for the following data shape: array of objects: { id: string, name: string, email: string, plan: 'free' | 'pro' | 'enterprise', signupDate: string (ISO date), mrr: number } REQUIREMENTS: - Columns: Name (sortable), Email, Plan, Signup Date (sortable), MRR (sortable) - Sorting: clicking a sortable column header toggles ascending/descending order, with a visible indicator of current sort state - Filtering: a single search input that filters rows by name and email, case-insensitive - Pagination: 15 rows per page, with previous/next controls and a current page indicator - Empty states: show a clear message when the data array is empty, and a separate message when a filter returns no results - Accessibility: sortable headers must be keyboard-operable and expose their sort state to screen readers - Styling approach: Tailwind CSS classes OUTPUT FORMAT: Return the complete component code in a single code block, followed by a short list of any assumptions you made about data or behavior that I didn't specify.

When to use it

  • Scaffolding an admin dashboard or internal tool that needs a sortable, filterable list view
  • Replacing a static HTML table with an interactive one without hand-writing sort and pagination logic
  • Prototyping a data-heavy UI quickly before deciding on a full table library
  • Teaching or demonstrating React state management patterns using a realistic, non-trivial component

Best practices

  • Specify the exact shape of the data array (field names and types) so the model doesn't invent mismatched prop names
  • State which columns need custom rendering, such as a date formatted as relative time or a status shown as a colored badge
  • Ask for the empty-state and no-results-after-filtering states explicitly, since models often skip them unless told
  • Request TypeScript types for props and state up front if your codebase uses TypeScript, rather than adding them after the fact

Common mistakes

  • Not specifying page size, which leaves the model guessing between 10, 20, or 25 rows per page
  • Leaving sort direction unspecified, so ascending/descending toggling behavior is inconsistent across columns
  • Forgetting to ask for keyboard and screen-reader accessibility on sortable column headers
  • Accepting the first version without testing it against an empty array or a single-row dataset

FAQs

How do I get ChatGPT to generate a React table with working sort and pagination in one pass?

Specify the exact data shape, which columns are sortable, the page size, and how filtering should match text, all before the model writes any code. Vague requests like "add sorting" tend to produce inconsistent behavior across columns because the model has to guess your intent for each one.

Should I ask for TypeScript types in the same prompt as the component?

Yes, if your project uses TypeScript, ask for prop and state types in the same request rather than adding them afterward. Retrofitting types onto an already-generated component often requires more back-and-forth than specifying them up front.

Why does the generated table break when the data array is empty?

Many generated components assume there's always at least one row, so sorting or pagination logic can throw or render incorrectly on an empty array. Explicitly requesting an empty-state message in the prompt is the most reliable fix.

Can this same prompt structure work for a table with server-side pagination instead of client-side?

Yes, but you need to change the requirements section to describe the API contract (what parameters the server expects for page, sort field, and sort direction) instead of assuming all data is already loaded client-side. The sorting and filtering logic then moves from the component to the API call.

What tool pairs well with this prompt for catching missing edge cases before I use it?

Prompt Debugger — it flags vague constraints and unhandled edge cases, like unspecified empty states or ambiguous sort behavior, that would otherwise show up as bugs after the component is already in your codebase.

Found this prompt useful? Share it.

Share

More in React Prompt Recipes

React Prompt Recipes

AI Prompt to Build a React Billing Dashboard Component Using Stripe's MCP Server

This prompt is for frontend developers who need to build a React billing dashboard component that shows a customer's live subscription, invo…

ROLE:
You are a senior React/TypeScript developer building a billing dashboard component for a SaaS product.

CONTEXT:
The component should display billing data for a customer, retrieved via Stripe's MCP server: [LIST_DATA_NEEDED_E.G._SUBSCRIPTION_PLAN_NEXT_CHARGE_DATE_PAYMENT_METHOD_RECENT_INVOICES]
Framework/styling: [REACT_VERSION_AND_STYLING_APPROACH_E.G._TAILWIND_CSS_MODULES]

CONSTRAINTS:
- Handle these billing states explicitly: [LIST_STATES_E.G._ACTIVE_PAST_DUE_CANCELED_PENDING_NO_PAYMENT_METHOD]
- Show a loading skeleton while data is being fetched, and a clear error state if the fetch fails
- Format currency and dates using the customer's actual locale/currency, not a hardcoded format
- Separate the data-fetching hook from the presentational component

OUTPUT FORMAT:
1. A short explanation of the component's structure (hook + presentational component)
2. The full TypeScript code, in a single fenced code block, with comments marking where each billing state is handled
3. A one-line note on any assumption you made about the data shape returned by the MCP server

Make this prompt yours

React Prompt Recipes

AI Prompt to Build a React Dark Mode Toggle with System Preference Detection

A React dark mode toggle prompt asks ChatGPT, Claude, or Gemini to generate a theme switching component that respects the user's OS level li…

Role: You are a senior React developer building a reusable UI component.

Context:
Framework/setup: [REACT VERSION, e.g. React 18 with Vite, Next.js App Router]
Styling approach: [CSS variables / Tailwind CSS dark class / CSS-in-JS library]
Component location/usage: [where the toggle will live, e.g. app header, settings page]

Task:
Build a dark mode toggle component with this exact behavior:
1. On first load, detect the user's OS preference via the `prefers-color-scheme` media query and use it as the initial theme, applied before the main content paints (no flash of the wrong theme).
2. If the user has previously made an explicit choice, that stored choice overrides the OS preference on future visits.
3. Persist the user's explicit choice in [STORAGE MECHANISM, e.g. localStorage].
4. Listen for theme changes made in other open tabs and update this tab's theme to match.
5. Expose the current theme and a toggle function via [CONTEXT/HOOK NAME, e.g. a useTheme hook] so other components can read and react to it.

Constraints:
- Use [STYLING APPROACH] to apply the theme, not inline style objects
- Include accessible labeling (aria-label or visible text) that reflects the current state
- Keep the component dependency-free unless [ALLOWED LIBRARIES] are specified

Output format:
Return the full component code in a fenced code block, followed by a short usage example showing how to wrap the app and consume the hook elsewhere.

Make this prompt yours

React Prompt Recipes

AI Prompt to Build a React Kanban Board With Drag-and-Drop

This prompt gives ChatGPT, Claude, or Gemini a complete specification for building a React Kanban board with drag and drop column reordering…

You are a senior React developer specializing in accessible, production-ready UI components.

Context:
- Framework: [REACT VERSION, e.g. React 18 with TypeScript]
- Drag-and-drop library: [LIBRARY NAME, e.g. @dnd-kit/core]
- Styling approach: [e.g. Tailwind CSS, CSS Modules, styled-components]
- Columns or workflow stages: [LIST OF COLUMN NAMES, e.g. Backlog, In Progress, Review, Done]
- State source: [e.g. local state, Zustand store, REST API endpoint]

Build a Kanban board component with the following requirements:
1. Render one column per workflow stage listed above, each showing its card count
2. Support dragging cards between columns and reordering cards within a column
3. Support keyboard-based reordering, not mouse-only interaction, for accessibility
4. Identify cards by a stable [ID FIELD NAME] field, never by array index
5. Call a [CALLBACK NAME] function on every successful move, passing the card id, source column, destination column, and new index
6. Show an optimistic UI update immediately, then roll back if [CALLBACK NAME] rejects
7. Handle empty columns and drops outside any valid column gracefully

Output format:
- The main board component
- Column and Card subcomponents
- Any custom hooks used for drag state
- A short usage example showing how to wire [CALLBACK NAME] to a real API call
- Brief notes on any library-specific setup required, such as providers, context, or CSS imports

Make this prompt yours