Skip to main content

Job application

Send it empty to see every field's error at once, then watch each one clear as you fix it. The interview has to fall before the first day, a rule that spans two fields, so the form checks it; the pickers already keep each value in its own range.

Loading…
import { useMemo, useState } from 'react';
import { ScrollView, StyleSheet, View } from 'react-native';
import {
  addDays,
  Button,
  CountryPicker,
  DatePickerField,
  DateTimePickerField,
  Heading,
  PhoneField,
  Select,
  Text,
  toDateKey,
  useTheme,
} from 'patine-ui';
import type { CountryCode } from 'patine-ui';

type Values = {
  role: string | null;
  country: CountryCode | null;
  phone: string;
  phoneValid: boolean;
  startDate: Date | null;
  interview: Date | null;
  skills: string[];
};
const EMPTY: Values = { role: null, country: null, phone: '', phoneValid: false, startDate: null, interview: null, skills: [] };
const ROLES = ['Frontend engineer', 'Mobile engineer', 'Product designer', 'Data analyst'].map((label) => ({ label, value: label }));
const SKILLS = ['React Native', 'TypeScript', 'Design systems', 'Accessibility', 'Testing', 'Animation'].map((label) => ({ label, value: label }));
const MIN_SKILLS = 2;
const MAX_SKILLS = 4;

/** Each field's error, left out once it's fine. */
const validate = (v: Values) => {
  const errors: Partial<Record<keyof Values, string>> = {
    role: v.role ? undefined : 'Choose the role you’re applying for',
    country: v.country ? undefined : 'Choose where you live',
    phone: !v.phone ? 'Enter a phone number' : v.phoneValid ? undefined : 'Enter the full number',
    startDate: v.startDate ? undefined : 'Choose when you can start',
    interview: !v.interview
      ? 'Choose an interview slot'
      : v.startDate && toDateKey(v.interview) >= toDateKey(v.startDate)
        ? 'Pick an interview before your first day'
        : undefined,
    skills: v.skills.length < MIN_SKILLS ? `Pick at least ${MIN_SKILLS} skills` : undefined,
  };
  return Object.fromEntries(Object.entries(errors).filter(([, error]) => error)) as typeof errors;
};

export default function JobApplication() {
  const { colors } = useTheme();
  const today = useMemo(() => {
    const day = new Date();
    day.setHours(0, 0, 0, 0);
    return day;
  }, []);
  const [values, setValues] = useState(EMPTY);
  const [submitted, setSubmitted] = useState(false);
  const [sending, setSending] = useState(false);
  const [sent, setSent] = useState(false);
  const errors = submitted ? validate(values) : {};
  const errorCount = Object.keys(errors).length;
  const set = <K extends keyof Values>(key: K) => (value: Values[K]) => setValues((current) => ({ ...current, [key]: value }));

  const send = () => {
    setSubmitted(true);
    if (Object.keys(validate(values)).length) return;
    setSending(true);
    setTimeout(() => {
      setSending(false);
      setSent(true);
    }, 1000);
  };

  return (
    <View style={[styles.screen, { backgroundColor: colors.background }]}>
      <ScrollView contentContainerStyle={styles.content} keyboardShouldPersistTaps="handled">
        <View style={styles.titles}>
          <Heading level={2}>Apply for a role</Heading>
          <Text color={errorCount ? 'danger' : 'textSecondary'}>
            {errorCount ? `${errorCount} ${errorCount === 1 ? 'field needs' : 'fields need'} attention` : 'Takes about a minute'}
          </Text>
        </View>
        <Select label="Role" required options={ROLES} value={values.role} onValueChange={set('role')} error={errors.role} />
        <CountryPicker label="Where you live" required value={values.country} onValueChange={set('country')} error={errors.country} />
        <PhoneField
          label="Phone"
          required
          value={values.phone}
          onValueChange={(phone, details) => setValues((current) => ({ ...current, phone, phoneValid: details.valid }))}
          error={errors.phone}
        />
        <DatePickerField
          label="First day"
          required
          helperText="From next week"
          value={values.startDate}
          onConfirm={set('startDate')}
          minDate={addDays(today, 7)}
          error={errors.startDate}
        />
        <DateTimePickerField
          label="Interview"
          required
          helperText="Before your first day"
          value={values.interview}
          onConfirm={set('interview')}
          minDate={addDays(today, 1)}
          minuteInterval={30}
          error={errors.interview}
        />
        <Select
          label="Skills"
          required
          multiple
          chips
          helperText={`${MIN_SKILLS} to ${MAX_SKILLS}`}
          options={SKILLS}
          value={values.skills}
          onValueChange={set('skills')}
          maxSelected={MAX_SKILLS}
          error={errors.skills}
        />
      </ScrollView>
      <View style={styles.footer}>
        <Button size="lg" loading={sending} disabled={sent} onPress={send}>
          {sent ? 'Application sent' : 'Send application'}
        </Button>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  screen: { flex: 1 },
  content: { gap: 14, padding: 20 },
  titles: { gap: 4, marginBottom: 4 },
  footer: { padding: 16 },
});

Components used​

How it works​

  • required and error on every field. required marks the label and tells screen readers; error turns the field red with its message under it, and replaces helperText while it's there.
  • Errors after the first try. validate runs on every render, but its result only shows once submitted is true, so each error clears the moment its field is fixed.
  • Cross-field rules live in the form. Each picker keeps its own value in range; that the interview comes before the first day involves two fields, so validate checks it.
  • With a form library, wire the fields the same way as in the forms guide: value and onValueChange on the selects, onConfirm on the date fields.