Skip to main content

Edit profile

A profile form with a photo, a name, a username, a bio that counts down its 160 characters, a date of birth that won't accept anyone under 13 and shows the age once picked, and a country with flags. Save lights up only when something changed.

Loading…
import { useState } from 'react';
import { ScrollView, StyleSheet, View } from 'react-native';
import { Avatar, Button, CountryPicker, DatePickerField, formatDate, Header, Link, TextArea, TextField, useTheme } from 'patine-ui';
import type { CountryCode } from 'patine-ui';

const MIN_AGE = 13;
const yearsAgo = (years: number) => {
  const day = new Date();
  day.setFullYear(day.getFullYear() - years);
  return day;
};
const ageOf = (birthday: Date) => {
  const now = new Date();
  const hadBirthday =
    now.getMonth() > birthday.getMonth() || (now.getMonth() === birthday.getMonth() && now.getDate() >= birthday.getDate());
  return now.getFullYear() - birthday.getFullYear() - (hadBirthday ? 0 : 1);
};

const SAVED = {
  name: 'Noa Peretz',
  username: 'noa.bakes',
  bio: 'Sourdough on weekends, product design on weekdays. Tel Aviv → Lisbon.',
  birthday: null as Date | null,
  country: 'PT' as CountryCode | null,
};

export default function EditProfile() {
  const { colors } = useTheme();
  const [profile, setProfile] = useState(SAVED);
  const [saved, setSaved] = useState(SAVED);
  const [saving, setSaving] = useState(false);
  const edit = (change: Partial<typeof SAVED>) => setProfile({ ...profile, ...change });
  const changed = JSON.stringify(profile) !== JSON.stringify(saved);
  const usernameError = /^[a-z0-9._]{3,}$/.test(profile.username) ? undefined : 'At least 3 letters, numbers, dots or underscores';

  const save = () => {
    setSaving(true);
    setTimeout(() => {
      setSaving(false);
      setSaved(profile);
    }, 900);
  };

  return (
    <View style={[styles.screen, { backgroundColor: colors.background }]}>
      <Header
        title="Edit profile"
        onBack={() => setProfile(saved)}
        backLabel="Cancel"
        actions={
          <Button size="sm" variant="ghost" loading={saving} disabled={!changed || !!usernameError} onPress={save}>
            Save
          </Button>
        }
      />
      <ScrollView contentContainerStyle={styles.form} keyboardShouldPersistTaps="handled">
        <View style={styles.photo}>
          <Avatar name={profile.name} src="https://picsum.photos/id/1027/240/240" size="lg" style={styles.avatar} />
          <Link onPress={() => {}}>Change photo</Link>
        </View>
        <TextField label="Name" value={profile.name} onValueChange={(name) => edit({ name })} autoComplete="name" />
        <TextField
          label="Username"
          prefix="@"
          value={profile.username}
          onValueChange={(username) => edit({ username: username.toLowerCase() })}
          error={usernameError}
          autoCapitalize="none"
          autoCorrect={false}
        />
        <TextArea
          label="Bio"
          value={profile.bio}
          onValueChange={(bio) => edit({ bio })}
          maxLength={160}
          showCount
          minRows={3}
        />
        <DatePickerField
          label="Date of birth"
          title="Birthday"
          placeholder="Add your birthday"
          helperText="Only your age is shown on your profile"
          value={profile.birthday ?? new Date(2000, 0, 1)}
          displayValue={
            profile.birthday
              ? `${formatDate(profile.birthday, undefined, { dateStyle: 'long' })} · ${ageOf(profile.birthday)}`
              : ''
          }
          onConfirm={(birthday) => edit({ birthday })}
          minDate={yearsAgo(110)}
          maxDate={yearsAgo(MIN_AGE)}
        />
        <CountryPicker label="Country" value={profile.country} onValueChange={(country) => edit({ country })} />
      </ScrollView>
    </View>
  );
}

const styles = StyleSheet.create({
  screen: { flex: 1 },
  form: { gap: 16, padding: 20 },
  photo: { alignItems: 'center', gap: 10, marginBottom: 8 },
  avatar: { width: 96, height: 96, borderRadius: 48 },
});

Components used​

The birthday field​

  • A minimum age. maxDate 13 years ago disables later days (and months and years on the wheels) and clamps the value, so an under-13 date can't be confirmed.
  • Placeholder until picked. value opens the calendar on 2000 before anything is picked, so displayValue is what keeps the placeholder showing until the reader confirms. Once they do, it shows the date and the age.
  • Years at a time. In the calendar, tap the month title to jump to a year. Some apps prefer display="wheel" for birthdays, since a year wheel reaches decades back in one flick; its column order follows the locale (M/D/Y in the US, D/M/Y in most of the world).
  • Store it as a day. Save birthdays as toDateKey(birthday) (YYYY-MM-DD): they're calendar days, not instants.