Cours React Native · Module 5: Formulaires

Picker, Switch et autres contrôles

3 min de lecture ·
Dans cette leçon5

React Native propose divers contrôles de formulaire.

Switch

import { Switch } from 'react-native';

function SettingsForm() {
  const [notifications, setNotifications] = useState(true);
  const [darkMode, setDarkMode] = useState(false);

  return (
    <View>
      <View style={styles.row}>
        <Text>Notifications</Text>
        <Switch
          value={notifications}
          onValueChange={setNotifications}
          trackColor={{ false: '#767577', true: '#81b0ff' }}
          thumbColor={notifications ? '#1a5276' : '#f4f3f4'}
          ios_backgroundColor="#3e3e3e"
        />
      </View>

      <View style={styles.row}>
        <Text>Mode sombre</Text>
        <Switch
          value={darkMode}
          onValueChange={setDarkMode}
        />
      </View>
    </View>
  );
}

Picker (expo)

npx expo install @react-native-picker/picker
import { Picker } from '@react-native-picker/picker';

function CountryPicker() {
  const [country, setCountry] = useState('us');

  return (
    <View style={styles.pickerContainer}>
      <Text style={styles.label}>Pays :</Text>
      <Picker
        selectedValue={country}
        onValueChange={(value) => setCountry(value)}
        style={styles.picker}
      >
        <Picker.Item label="États-Unis" value="us" />
        <Picker.Item label="Allemagne" value="de" />
        <Picker.Item label="France" value="fr" />
        <Picker.Item label="Italie" value="it" />
      </Picker>
    </View>
  );
}

Checkbox personnalisée

import { Pressable, View, Text } from 'react-native';
import { Ionicons } from '@expo/vector-icons';

interface CheckboxProps {
  checked: boolean;
  onChange: (checked: boolean) => void;
  label: string;
}

function Checkbox({ checked, onChange, label }: CheckboxProps) {
  return (
    <Pressable
      style={styles.checkboxContainer}
      onPress={() => onChange(!checked)}
    >
      <View style={[styles.checkbox, checked && styles.checkboxChecked]}>
        {checked && <Ionicons name="checkmark" size={16} color="#fff" />}
      </View>
      <Text style={styles.checkboxLabel}>{label}</Text>
    </Pressable>
  );
}

const styles = StyleSheet.create({
  checkboxContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginVertical: 8,
  },
  checkbox: {
    width: 24,
    height: 24,
    borderWidth: 2,
    borderColor: '#1a5276',
    borderRadius: 4,
    justifyContent: 'center',
    alignItems: 'center',
  },
  checkboxChecked: {
    backgroundColor: '#1a5276',
  },
  checkboxLabel: {
    marginLeft: 10,
    fontSize: 16,
  },
});

Boutons radio

interface RadioOption {
  value: string;
  label: string;
}

interface RadioGroupProps {
  options: RadioOption[];
  value: string;
  onChange: (value: string) => void;
}

function RadioGroup({ options, value, onChange }: RadioGroupProps) {
  return (
    <View>
      {options.map((option) => (
        <Pressable
          key={option.value}
          style={styles.radioContainer}
          onPress={() => onChange(option.value)}
        >
          <View style={styles.radio}>
            {value === option.value && <View style={styles.radioSelected} />}
          </View>
          <Text style={styles.radioLabel}>{option.label}</Text>
        </Pressable>
      ))}
    </View>
  );
}

// Utilisation
function PaymentForm() {
  const [paymentMethod, setPaymentMethod] = useState('card');

  return (
    <RadioGroup
      options={[
        { value: 'card', label: 'Carte bancaire' },
        { value: 'paypal', label: 'PayPal' },
        { value: 'transfer', label: 'Virement bancaire' },
      ]}
      value={paymentMethod}
      onChange={setPaymentMethod}
    />
  );
}

Sélecteur de date/heure

npx expo install @react-native-community/datetimepicker
import DateTimePicker from '@react-native-community/datetimepicker';

function DatePicker() {
  const [date, setDate] = useState(new Date());
  const [show, setShow] = useState(false);

  const onChange = (event: any, selectedDate?: Date) => {
    setShow(Platform.OS === 'ios');
    if (selectedDate) {
      setDate(selectedDate);
    }
  };

  return (
    <View>
      <Pressable onPress={() => setShow(true)} style={styles.dateButton}>
        <Text>{date.toLocaleDateString('fr-FR')}</Text>
      </Pressable>

      {show && (
        <DateTimePicker
          value={date}
          mode="date"
          display="default"
          onChange={onChange}
          locale="fr-FR"
        />
      )}
    </View>
  );
}

Des contrôles variés te permettent de créer des formulaires intuitifs !

Code de cette leçon : App.tsx
import React, { useState } from 'react';
import { View, Text, Pressable, StyleSheet } from 'react-native';
import { Ionicons } from '@expo/vector-icons';

interface CheckboxProps {
  checked: boolean;
  onChange: (checked: boolean) => void;
  label: string;
}

function Checkbox({ checked, onChange, label }: CheckboxProps) {
  return (
    <Pressable
      style={styles.checkboxContainer}
      // TODO : dans onPress, appelle onChange(!checked) pour inverser la sélection
    >
      <View style={[styles.checkbox, checked && styles.checkboxChecked]}>
        {/* TODO : si checked === true, affiche <Ionicons name="checkmark" size={16} color="#fff" /> */}
      </View>
      <Text style={styles.checkboxLabel}>{label}</Text>
    </Pressable>
  );
}

export default function App() {
  const [accepted, setAccepted] = useState(false);

  return (
    <View style={styles.container}>
      <Checkbox
        checked={accepted}
        onChange={setAccepted}
        label="J'accepte les conditions de l'Atlantide"
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    justifyContent: 'center',
    backgroundColor: '#1a5276',
  },
  checkboxContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  checkbox: {
    width: 24,
    height: 24,
    borderWidth: 2,
    borderColor: '#aed6f1',
    borderRadius: 4,
    justifyContent: 'center',
    alignItems: 'center',
  },
  checkboxChecked: {
    backgroundColor: '#2980b9',
    borderColor: '#2980b9',
  },
  checkboxLabel: {
    marginLeft: 10,
    fontSize: 16,
    color: '#fff',
  },
});

Entrées de la documentation utilisées dans cette leçon

Tu as repéré une erreur dans cette leçon ?

Teste tes connaissances

Réponds aux questions de cette leçon. Choisis une réponse pour voir tout de suite si elle est correcte.

  1. 1. Quel composant sert aux interrupteurs on/off ?

  2. 2. Quelle bibliothèque sert à la sélection de date dans Expo ?

Tâches pratiques dans le jeu

  • Tri horizontal

    Ordonne un Picker de base :

  • Éditeur de code

    Complète le code de Checkbox avec Pressable et une icône.

Articles utiles