DEV Community

Cover image for Build a React reporting filter with controlled dates: Presets & Validation
Maks
Maks

Posted on AI-assisted

Build a React reporting filter with controlled dates: Presets & Validation

Let's talk about date-range picker - it's just one part of a reporting filter. Seems easy, right? But the app still needs to decide when a selection takes effect, what “Last 7 days” includes, and what happens when someone requests a range the report cannot support.

We are going to build a simple React app with fictional invoice data, a revenue total, two presets and an explicit Apply filters action.

Expected: four invoices totaling $4,000.00. Choosing This month changes the selected dates; pressing Apply filters changes the report to seven invoices totaling $5,330.00. That distinction is the main idea of the implementation.

Define the reporting rules

The example uses these rules:

  • Dates are normalized YYYY-MM-DD business dates, not timestamps.
  • Both endpoints are included. November 10–16 is seven days.
  • Editing the picker or choosing a preset changes a draft selection.
  • Apply filters validates the draft before replacing the applied selection.
  • A report can include at most 31 calendar days.
  • A rejected range leaves the previous report visible.
  • Reset restores both selections to the initial seven-day range.

The reference date is deliberately frozen at November 16, 2026. “This month” means November 1–16, or month-to-date. A fixed date makes the code and expected totals reproducible whenever someone reads the article.

For a production reporting screen, obtain the reporting date in the business's chosen timezone. The browser's current date might differ from the date used by your accounting or reporting service.

Get the complete example

The complete runnable source is available on GitHub. You can also download the source ZIP.

git clone https://github.com/revolist/revo-ui-react-date-filter.git
cd revo-ui-react-date-filter
npm ci
npm run dev
Enter fullscreen mode Exit fullscreen mode

The following sections explain how to build the same project step by step.

Create a small React project

The example uses React 19.2.0 and published @revolist/ui@4.0.25, including the public @revolist/ui/dates helpers. Start with Node.js 22.18 or newer:

mkdir react-date-report
cd react-date-report
npm init -y
npm pkg set type=module
npm pkg set 'scripts.dev=vite' 'scripts.build=tsc --noEmit && vite build'
npm install --save-exact react@19.2.0 react-dom@19.2.0 @revolist/ui@4.0.25
npm install --save-dev --save-exact vite@8.2.4 typescript@6.0.3 @types/react@19.2.2 @types/react-dom@19.2.1 @types/node@24.19.2
mkdir src
Enter fullscreen mode Exit fullscreen mode

Create vite.config.ts. For this release, excluding the UI adapter from prebundling avoids an unresolved optional PDF stylesheet during development. React dependencies still need prebundling for their CommonJS exports:

import { defineConfig } from 'vite';

export default defineConfig({
  // Preserve optional PDF imports in Revo UI 4.0.25 during development.
  optimizeDeps: {
    exclude: ['@revolist/ui', '@revolist/ui/react'],
    include: ['react', 'react-dom', 'react-dom/client'],
  },
});
Enter fullscreen mode Exit fullscreen mode

Create index.html:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>React date-range report</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.tsx"></script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Create tsconfig.json:

{
  "compilerOptions": {
    "target": "ES2022",
    "lib": ["ES2022", "DOM", "DOM.Iterable"],
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "jsx": "react-jsx",
    "allowImportingTsExtensions": true,
    "noEmit": true,
    "strict": true,
    "skipLibCheck": true,
    "verbatimModuleSyntax": true,
    "types": ["vite/client", "node"]
  },
  "include": ["src"]
}
Enter fullscreen mode Exit fullscreen mode

Revo UI's named React components load their required styles automatically in this release. The app's own layout is separate; no RevoGrid instance is required for this filter. See the React integration guide for other styling and integration options.

Model dates without accidental timezone shifts

Create src/report.ts:

import {
  addDays, diffInCalendarDays, formatCalendarDateDisplay,
  isValidIsoDate, startOfMonth,
} from '@revolist/ui/dates';
import type { CalendarDateRange } from '@revolist/ui/calendar/types';

export type DateRange = CalendarDateRange;
export type Order = { id: string; bookedOn: string; customer: string; cents: number };

// A frozen reporting date keeps the tutorial reproducible next month or year.
export const REFERENCE_DATE = '2026-11-16';
export const EARLIEST_DATE = '2026-10-01';
export const MAX_REPORT_DAYS = 31;
export function inclusiveDays(range: DateRange): number {
  return diffInCalendarDays(range.from, range.to) + 1;
}

export function presetRange(preset: 'last7' | 'month', reference = REFERENCE_DATE): DateRange {
  if (!isValidIsoDate(reference)) throw new Error('Expected a valid reporting date.');
  return {
    from: preset === 'last7' ? addDays(reference, -6) : startOfMonth(reference),
    to: reference,
  };
}

export function validateRange(range: DateRange): string {
  if (!isValidIsoDate(range.from) || !isValidIsoDate(range.to)) {
    return 'Choose two valid dates in YYYY-MM-DD format.';
  }
  if (range.from > range.to) return 'The start date must not be after the end date.';
  if (range.from < EARLIEST_DATE || range.to > REFERENCE_DATE) {
    return `Choose dates from ${EARLIEST_DATE} through ${REFERENCE_DATE}.`;
  }
  if (inclusiveDays(range) > MAX_REPORT_DAYS) {
    return `Choose at most ${MAX_REPORT_DAYS} calendar days, including both endpoints.`;
  }
  return '';
}

// Fixture values are fictional; cents avoid floating-point addition for totals.
export const ORDERS: readonly Order[] = [
  { id: 'INV-101', bookedOn: '2026-10-01', customer: 'North Studio', cents: 89000 },
  { id: 'INV-102', bookedOn: '2026-10-15', customer: 'Atlas Works', cents: 25000 },
  { id: 'INV-103', bookedOn: '2026-10-31', customer: 'Fern Systems', cents: 120000 },
  { id: 'INV-104', bookedOn: '2026-11-01', customer: 'North Studio', cents: 45000 },
  { id: 'INV-105', bookedOn: '2026-11-03', customer: 'Orbit Design', cents: 67000 },
  { id: 'INV-106', bookedOn: '2026-11-09', customer: 'Atlas Works', cents: 21000 },
  { id: 'INV-107', bookedOn: '2026-11-10', customer: 'North Studio', cents: 125000 },
  { id: 'INV-108', bookedOn: '2026-11-12', customer: 'Fern Systems', cents: 33000 },
  { id: 'INV-109', bookedOn: '2026-11-14', customer: 'Orbit Design', cents: 190000 },
  { id: 'INV-110', bookedOn: '2026-11-16', customer: 'Atlas Works', cents: 52000 },
];

export function filterOrders(orders: readonly Order[], range: DateRange): Order[] {
  return orders.filter(order => order.bookedOn >= range.from && order.bookedOn <= range.to);
}

export function totalCents(orders: readonly Order[]): number {
  return orders.reduce((sum, order) => sum + order.cents, 0);
}

export function formatMoney(cents: number): string {
  return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(cents / 100);
}

export function formatDate(value: string, locale = 'en-GB'): string {
  return formatCalendarDateDisplay(value, locale) ?? '';
}
Enter fullscreen mode Exit fullscreen mode

The DateRange type comes from the package's public calendar types. The shared isValidIsoDate helper narrows values to plain calendar dates and rejects timestamps and impossible dates such as February 29 in a non-leap year.

After validation, comparing normalized date strings is sufficient for this dataset. Each string has the same year-month-day format, so lexical order is chronological order. That is why filterOrders can compare bookedOn directly with from and to.

Revo UI owns the date mechanics: addDays uses UTC arithmetic, startOfMonth resolves the first day of the month, and diffInCalendarDays returns the signed day difference. The example adds one because its reporting policy includes both endpoints. formatCalendarDateDisplay formats a civil date without shifting it to another day in the browser's timezone; the formatDate wrapper chooses the report locale. For example, formatDate('2026-11-16', 'fr-FR') produces 16 nov. 2026. The 31-day limit, permitted reporting bounds, and invoice filtering remain application rules.

This approach does not define a timestamp-reporting policy. If your rows contain instants such as 2026-11-16T23:30:00Z, calculate business-timezone boundaries on the server. A half-open interval—start inclusive, next-day start exclusive—is usually easier to express than “23:59:59.999.”

The fixture stores money in cents, which keeps the additions in this small example integral. Financial systems may need a decimal money type and explicit currency rules beyond this tutorial.

Keep draft and applied dates separate

Create src/App.tsx:

import { useState } from 'react';
import { Button, DateRangePicker } from '@revolist/ui/react';
import {
  EARLIEST_DATE, ORDERS, REFERENCE_DATE, filterOrders, formatDate,
  formatMoney, inclusiveDays, presetRange, totalCents, validateRange,
} from './report.ts';
import type { DateRange } from './report.ts';

export default function App() {
  const [draft, setDraft] = useState<DateRange>(() => presetRange('last7'));
  const [applied, setApplied] = useState<DateRange>(() => presetRange('last7'));
  const [error, setError] = useState('');
  const [notice, setNotice] = useState('Showing the last 7 days in the demo data.');
  const dirty = draft.from !== applied.from || draft.to !== applied.to;
  const rows = filterOrders(ORDERS, applied);

  function changeDraft(next: DateRange) {
    setDraft(next);
    setError('');
    setNotice('');
  }

  function apply() {
    const message = validateRange(draft);
    setError(message);
    if (message) return; // Keep the previous report visible on failure.
    setApplied({ ...draft });
    setNotice(`Applied ${formatDate(draft.from)} to ${formatDate(draft.to)}.`);
  }

  function reset() {
    const initial = presetRange('last7');
    setDraft(initial);
    setApplied(initial);
    setError('');
    setNotice('Reset to the last 7 days in the demo data.');
  }

  return (
    <main>
      <header className="page-header">
        <div><p className="eyebrow">Reporting / React recipe</p><h1>Revenue report</h1></div>
        <span className="fixture-note">Fictional data · as of {formatDate(REFERENCE_DATE)}</span>
      </header>

      <section className="filter-panel" aria-labelledby="filter-heading">
        <div className="section-heading">
          <div><h2 id="filter-heading">Report window</h2><p>Choose a range, then apply it to the report.</p></div>
          <span className="rule">Maximum 31 days</span>
        </div>
        <div className="presets" role="group" aria-label="Date presets">
          <Button type="button" variant="secondary" onClick={() => changeDraft(presetRange('last7'))}>Last 7 days</Button>
          <Button type="button" variant="secondary" onClick={() => changeDraft(presetRange('month'))}>This month</Button>
        </div>
        <DateRangePicker
          label="Report dates"
          fromLabel="Start date"
          toLabel="End date"
          openLabel="Choose report dates"
          value={draft}
          onChange={changeDraft}
          minDate={EARLIEST_DATE}
          maxDate={REFERENCE_DATE}
          referenceDate={REFERENCE_DATE}
          captionLayout="dropdown"
          weekStartsOn={1}
        />
        <p className="hint">“This month” means 1–16 November in this frozen example. Dates include both endpoints.</p>
        {error && <p className="error" role="alert">{error}</p>}
        <div className="filter-actions">
          <Button type="button" variant="primary" onClick={apply}>Apply filters</Button>
          <Button type="button" variant="ghost" onClick={reset}>Reset</Button>
          <span className={dirty ? 'pending' : 'applied'} data-testid="filter-state">
            {dirty ? 'Unapplied changes' : 'Filters applied'}
          </span>
        </div>
        <p className="notice" role="status">{notice}</p>
      </section>

      <section className="results" aria-labelledby="results-heading">
        <div className="results-heading">
          <div><p className="eyebrow">Applied range</p><h2 id="results-heading">{formatDate(applied.from)} – {formatDate(applied.to)}</h2></div>
          <span className="day-count">{inclusiveDays(applied)} calendar days</span>
        </div>
        <div className="metrics">
          <div><span>Booked revenue</span><strong data-testid="revenue">{formatMoney(totalCents(rows))}</strong></div>
          <div><span>Invoices</span><strong data-testid="invoice-count">{rows.length}</strong></div>
        </div>
        <div className="table-scroll">
          <table>
            <caption className="sr-only">Invoices matching the applied date range</caption>
            <thead><tr><th scope="col">Invoice</th><th scope="col">Booked date</th><th scope="col">Customer</th><th scope="col" className="amount">Amount</th></tr></thead>
            <tbody>
              {rows.map(order => <tr key={order.id}><td>{order.id}</td><td>{formatDate(order.bookedOn)}</td><td>{order.customer}</td><td className="amount">{formatMoney(order.cents)}</td></tr>)}
              {rows.length === 0 && <tr><td colSpan={4} className="empty">No invoices in this range. Choose another date window.</td></tr>}
            </tbody>
          </table>
        </div>
      </section>
      <footer>Date controls: <a href="https://ui.rv-grid.com/components/calendar-and-dates/">Revo UI</a>. Filtering and reporting rules belong to this example.</footer>
    </main>
  );
}
Enter fullscreen mode Exit fullscreen mode

There are two date states for a reason:

const [draft, setDraft] = useState<DateRange>(() => presetRange('last7'));
const [applied, setApplied] = useState<DateRange>(() => presetRange('last7'));
const rows = filterOrders(ORDERS, applied);
Enter fullscreen mode Exit fullscreen mode

The picker receives draft; the report receives applied. The dirty comparison makes that distinction visible as Unapplied changes. A user can explore dates without changing the totals underneath them.

The preset buttons use ordinary React state updates. They do not depend on a speculative range-preset property: in this package version, the calendar's presets option describes individual dates. Explicit buttons let the application define exactly what a reporting preset means.

Distinguish picker behavior from report validation

The picker handles calendar interaction, and its minDate and maxDate constrain date entry. In version 4.0.25, it also normalizes reversed endpoints and does not emit invalid date strings as new values.

The application therefore should not pretend that an impossible text entry or a reversed range necessarily reaches onChange. Those are different concerns from the report's 31-day maximum, which is enforced in apply().

Try selecting October 1 through November 16. The individual dates are within the allowed bounds, but the range spans too many days. Pressing Apply filters displays an explanation and keeps the previous table and revenue total. The rejected draft remains available for correction.

The date checks in validateRange also provide defensive validation for future entry points, such as saved filters or URL parameters. On a server-backed report, repeat the relevant rules on the server; UI validation is not an authorization or data-integrity boundary.

Mount the screen

Create src/main.tsx:

import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App.tsx';
import './styles.css';

createRoot(document.getElementById('root')!).render(
  <StrictMode><App /></StrictMode>,
);
Enter fullscreen mode Exit fullscreen mode

Run the project:

npm run dev
Enter fullscreen mode Exit fullscreen mode

Use npm run build to type-check and create a production build.

Check the transitions, not only the picker

These are the useful checks for this example:

Action Expected result
Load the screen November 10–16; 4 invoices; $4,000.00
Choose This month The draft starts November 1; the report still shows $4,000.00
Press Apply filters November 1–16; 7 invoices; $5,330.00
Select October 1–November 16 and apply A 31-day-limit error; the previous result remains visible
Press Reset Both date states return to November 10–16 and the error clears
Apply November 5–6 An empty result and $0.00, rather than an error

For date helpers, include a month boundary, a leap day, both inclusive endpoints, and the 31-day/32-day boundary. Those cases exercise date arithmetic and range boundaries directly.

When the report moves to an API, preserve the same state distinction. Validate the draft, send the intended range, and update the applied result only according to an explicit success/error policy. That keeps the dates displayed above the table consistent with the data the user is actually looking at.

References

Top comments (0)