PPolaris ComponentsConnect an agent

Date Range Picker

The Shopify analytics date range control: a calendar button opening a popover with preset ranges, editable since/until fields and a two-month range calendar.

Preview

Code

Example.jsx
import { useCallback, useEffect, useMemo, useState } from 'react';
import { BlockStack, Box, Button, DatePicker, Icon, InlineGrid, InlineStack, OptionList, Popover, Scrollable, TextField, useBreakpoints } from '@shopify/polaris';
import { ArrowRightIcon, CalendarIcon } from '@shopify/polaris-icons';

const startOfDay = (date) => new Date(new Date(date).setHours(0, 0, 0, 0));

const daysAgo = (days) => {
  const date = startOfDay(new Date());
  date.setDate(date.getDate() - days);
  return date;
};

const formatDate = (date) =>
  [
    date.getFullYear(),
    String(date.getMonth() + 1).padStart(2, '0'),
    String(date.getDate()).padStart(2, '0'),
  ].join('-');

const sameDay = (a, b) => a.toDateString() === b.toDateString();

export const Example = () => {
  const { mdDown } = useBreakpoints();
  const [popoverActive, setPopoverActive] = useState(false);
  const [selection, setSelection] = useState(null);

  const ranges = useMemo(() => {
    const today = startOfDay(new Date());
    const yesterday = daysAgo(1);
    return [
      { title: 'Today', period: { since: today, until: today } },
      { title: 'Yesterday', period: { since: yesterday, until: yesterday } },
      { title: 'Last 7 days', period: { since: daysAgo(7), until: yesterday } },
      { title: 'Last 30 days', period: { since: daysAgo(30), until: yesterday } },
      { title: 'Last 90 days', period: { since: daysAgo(90), until: yesterday } },
      { title: 'Last 365 days', period: { since: daysAgo(365), until: yesterday } },
    ];
  }, []);

  const defaultRange = useMemo(() => {
    if (!selection) return ranges[0];
    const matched = ranges.find(
      (range) =>
        sameDay(range.period.since, selection.start) && sameDay(range.period.until, selection.end),
    );
    return matched ?? { title: 'Custom', period: { since: selection.start, until: selection.end } };
  }, [ranges, selection]);

  const [activeRange, setActiveRange] = useState(defaultRange);
  const [{ month, year }, setVisibleMonth] = useState({
    month: defaultRange.period.since.getMonth(),
    year: defaultRange.period.since.getFullYear(),
  });

  const handleMonthChange = useCallback((nextMonth, nextYear) => {
    setVisibleMonth({ month: nextMonth, year: nextYear });
  }, []);

  useEffect(() => {
    setVisibleMonth({
      month: activeRange.period.since.getMonth(),
      year: activeRange.period.since.getFullYear(),
    });
  }, [activeRange]);

  return (
    <Popover
      active={popoverActive}
      autofocusTarget="none"
      preferredAlignment="left"
      preferredPosition="below"
      fluidContent
      sectioned={false}
      fullHeight
      activator={
        <Button
          icon={CalendarIcon}
          size="slim"
          onClick={() => setPopoverActive((prev) => !prev)}
        >
          {activeRange.title}
        </Button>
      }
      onClose={() => setPopoverActive(false)}
    >
      <Popover.Pane fixed>
        <Box padding="400">
          <InlineGrid columns={{ xs: '1fr', md: 'max-content max-content' }} gap="400">
            <Box maxWidth="212px" width="100%">
              <Scrollable style={{ height: 'auto' }}>
                <OptionList
                  options={ranges.map((range) => ({ value: range.title, label: range.title }))}
                  selected={[activeRange.title]}
                  onChange={(selected) => {
                    const next = ranges.find((range) => range.title === selected[0]);
                    if (next) setActiveRange(next);
                  }}
                />
              </Scrollable>
            </Box>
            <Box maxWidth="516px">
              <BlockStack gap="400">
                <InlineStack gap="200" blockAlign="center" wrap={false}>
                  <div style={{ flexGrow: 1 }}>
                    <TextField
                      label="Since"
                      role="combobox"
                      value={formatDate(activeRange.period.since)}
                      autoComplete="off"
                      readOnly
                    />
                  </div>
                  {mdDown ? null : (
                    <Box paddingBlockStart="600">
                      <Icon source={ArrowRightIcon} tone="subdued" />
                    </Box>
                  )}
                  <div style={{ flexGrow: 1 }}>
                    <TextField
                      label="Until"
                      role="combobox"
                      value={formatDate(activeRange.period.until)}
                      autoComplete="off"
                      readOnly
                    />
                  </div>
                </InlineStack>
                <div>
                  <DatePicker
                    month={month}
                    year={year}
                    selected={{
                      start: activeRange.period.since,
                      end: activeRange.period.until,
                    }}
                    onChange={({ start, end }) =>
                      setActiveRange({ title: 'Custom', period: { since: start, until: end } })
                    }
                    onMonthChange={handleMonthChange}
                    multiMonth={!mdDown}
                    allowRange
                  />
                </div>
              </BlockStack>
            </Box>
          </InlineGrid>
        </Box>
      </Popover.Pane>
      <Popover.Pane fixed>
        <Popover.Section>
          <InlineStack align="end" gap="200">
            <Button
              onClick={() => {
                setActiveRange(defaultRange);
                setPopoverActive(false);
              }}
            >
              Cancel
            </Button>
            <Button
              variant="primary"
              onClick={() => {
                setSelection({
                  start: activeRange.period.since,
                  end: activeRange.period.until,
                });
                setPopoverActive(false);
              }}
            >
              Apply
            </Button>
          </InlineStack>
        </Popover.Section>
      </Popover.Pane>
    </Popover>
  );
};