React Native

Apps mobiles natives avec React - partage de code web, hot reload, performance native

TL;DR

Quoi : Créer des apps mobiles natives avec React et JavaScript.

Pourquoi : Partage de code avec React web, hot reloading, performance native, large écosystème.

Quick Start

Créer un nouveau projet :

npx create-expo-app@latest my-app
cd my-app
npx expo start

Ou avec React Native CLI :

npx @react-native-community/cli init MyApp
cd MyApp
npx react-native run-ios    # or run-android

Cheatsheet

ConceptReact Native
Conteneur<View>
Texte<Text>
Image<Image>
Bouton<TouchableOpacity>, <Pressable>
Liste<FlatList>, <ScrollView>
Entrée<TextInput>

Gotchas

Composant de base

import { View, Text, StyleSheet } from 'react-native';

export default function App() {
  return (
    <View style={styles.container}>
      <Text style={styles.title}>Hello, React Native!</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff',
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
  },
});

Styling

import { StyleSheet, View } from 'react-native';

// StyleSheet
const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    backgroundColor: '#f5f5f5',
  },
  row: {
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
});

// Inline styles
<View style={{ marginTop: 10, padding: 5 }} />

// Multiple styles
<View style={[styles.container, styles.row]} />

Listes

import { FlatList, Text, View } from 'react-native';

const data = [
  { id: '1', title: 'Item 1' },
  { id: '2', title: 'Item 2' },
];

function MyList() {
  return (
    <FlatList
      data={data}
      keyExtractor={item => item.id}
      renderItem={({ item }) => (
        <View>
          <Text>{item.title}</Text>
        </View>
      )}
    />
  );
}
npm install @react-navigation/native @react-navigation/native-stack
npm install react-native-screens react-native-safe-area-context
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';

const Stack = createNativeStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="Details" component={DetailsScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

// Navigate
navigation.navigate('Details', { itemId: 42 });

// Get params
const { itemId } = route.params;

Gestion d’état

import { useState } from 'react';
import { View, Text, Button } from 'react-native';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <View>
      <Text>Count: {count}</Text>
      <Button title="Increment" onPress={() => setCount(count + 1)} />
    </View>
  );
}

Next Steps