PPolaris ComponentsConnect an agent

InlineError

A field-level error message with a warning icon, used to explain a validation problem next to a control that has no built-in error prop.

Preview

Code

Example.jsx
import { useState, useCallback } from 'react';
import { Card, Box, BlockStack, InlineStack, InlineError, TextField, Button, ButtonGroup, Text, Labelled } from '@shopify/polaris';

const WEEKDAYS = [
  { id: 'mon', label: 'Mon' },
  { id: 'tue', label: 'Tue' },
  { id: 'wed', label: 'Wed' },
  { id: 'thu', label: 'Thu' },
  { id: 'fri', label: 'Fri' },
  { id: 'sat', label: 'Sat' },
  { id: 'sun', label: 'Sun' },
];

const CODE_FIELD_ID = 'discount-code';
const DAYS_FIELD_ID = 'active-days';

export const Example = () => {
  const [code, setCode] = useState('summer sale');
  const [days, setDays] = useState([]);
  const [validated, setValidated] = useState(true);

  const codeError = /\s/.test(code) ? 'Discount codes cannot contain spaces.' : '';
  const daysError = validated && days.length === 0 ? 'Select at least one day to run this discount.' : '';

  const toggleDay = useCallback((id) => {
    setDays((prev) => (prev.includes(id) ? prev.filter((day) => day !== id) : [...prev, id]));
    setValidated(true);
  }, []);

  return (
    <Card>
      <BlockStack gap="400">
        <Text as="h2" variant="headingMd">
          Discount schedule
        </Text>

        <BlockStack gap="100">
          <TextField
            label="Discount code"
            id={CODE_FIELD_ID}
            value={code}
            onChange={setCode}
            autoComplete="off"
            error={Boolean(codeError)}
          />
          <InlineError message={codeError} fieldID={CODE_FIELD_ID} />
        </BlockStack>

        <BlockStack gap="100">
          <Labelled id={DAYS_FIELD_ID} label="Active days">
            <Box id={DAYS_FIELD_ID}>
              <InlineStack gap="200">
                <ButtonGroup variant="segmented">
                  {WEEKDAYS.map((day) => (
                    <Button
                      key={day.id}
                      pressed={days.includes(day.id)}
                      onClick={() => toggleDay(day.id)}
                    >
                      {day.label}
                    </Button>
                  ))}
                </ButtonGroup>
              </InlineStack>
            </Box>
          </Labelled>
          <InlineError message={daysError} fieldID={DAYS_FIELD_ID} />
        </BlockStack>

        <Text as="p" tone="subdued">
          {days.length === 0
            ? 'This discount will never run.'
            : `Runs on ${days.length} day${days.length === 1 ? '' : 's'} each week.`}
        </Text>
      </BlockStack>
    </Card>
  );
};