Skip to content

React Native - Boutons

React Native - Boutons et éléments tactiles

Section titled “React Native - Boutons et éléments tactiles”

React Native offre plusieurs façons de créer des boutons interactifs et des zones tactiles. Ce chapitre couvre le composant Button de base et des composants tactiles plus personnalisables comme TouchableOpacity, TouchableHighlight, TouchableWithoutFeedback et le moderne Pressable.

Le composant Button est un bouton simple et pré-stylisé. Il est utile pour une utilisation rapide mais offre une personnalisation limitée.

ButtonExample.js

import React from 'react';
import { View, Button, Alert, StyleSheet } from 'react-native';
const ButtonExample = () => {
const handlePress = () => {
Alert.alert('Button Pressed!', 'You tapped the basic button.');
};
return (
<View style={styles.container}>
<Button
title="Press Me"
onPress={handlePress}
color="#841584" // Optional: customize color (iOS text, Android background)
// accessibilityLabel="Learn more about this purple button" // For accessibility
// disabled={true} // To disable the button
/>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 20,
}
});
export default ButtonExample;

Ceci affichera un bouton standard de la plateforme. Sur iOS, la prop color modifie la couleur du texte. Sur Android, color modifie la couleur de fond (pour Android API niveau 21+).

TouchableOpacity est un wrapper qui atténue l’opacité de son contenu lorsqu’il est pressé, offrant un retour visuel. Il est hautement personnalisable car vous pouvez styliser ses composants enfants.

TouchableOpacityExample.js

import React from 'react';
import { View, TouchableOpacity, Text, StyleSheet, Alert } from 'react-native';
const TouchableOpacityExample = () => {
return (
<View style={styles.container}>
<TouchableOpacity
style={styles.touchableOpacityButton}
onPress={() => Alert.alert('TouchableOpacity', 'Opacity effect on press!')}
activeOpacity={0.7} // Opacity when active (pressed), default is 0.2
>
<Text style={styles.buttonText}>Custom Button (Opacity)</Text>
</TouchableOpacity>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1, justifyContent: 'center', alignItems: 'center', padding: 20
},
touchableOpacityButton: {
backgroundColor: '#007bff',
paddingVertical: 12,
paddingHorizontal: 25,
borderRadius: 8,
elevation: 3, // Android shadow
shadowColor: '#000', // iOS shadow
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.25,
shadowRadius: 3.84,
},
buttonText: {
color: 'white',
fontSize: 16,
fontWeight: 'bold',
textAlign: 'center',
}
});
export default TouchableOpacityExample;

Appuyer sur ce bouton réduira momentanément son opacité, offrant un retour tactile courant.

TouchableHighlight assombrit l’arrière-plan de son contenu (l’underlay) lorsqu’il est pressé. Vous devez fournir une prop underlayColor.

TouchableHighlightExample.js

import React from 'react';
import { View, TouchableHighlight, Text, StyleSheet, Alert } from 'react-native';
const TouchableHighlightExample = () => {
return (
<View style={styles.container}>
<TouchableHighlight
style={styles.touchableHighlightButton}
onPress={() => Alert.alert('TouchableHighlight', 'Highlight effect on press!')}
underlayColor="#0056b3" // Color shown when pressed
>
<Text style={styles.buttonText}>Custom Button (Highlight)</Text>
</TouchableHighlight>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1, justifyContent: 'center', alignItems: 'center', padding: 20
},
touchableHighlightButton: {
backgroundColor: '#17a2b8',
paddingVertical: 12,
paddingHorizontal: 25,
borderRadius: 8,
},
buttonText: {
color: 'white',
fontSize: 16,
fontWeight: 'bold',
textAlign: 'center',
}
});
export default TouchableHighlightExample;

Lorsqu’il est pressé, l’arrière-plan du bouton changera pour la underlayColor.

Pressable est un composant de base plus moderne et polyvalent qui détecte les différentes étapes des interactions de pression sur son enfant défini. Il offre un contrôle plus précis sur le retour visuel et les états d’interaction (par exemple, pressé, survolé, focus).

PressableExample.js

import React from 'react';
import { View, Pressable, Text, StyleSheet, Alert } from 'react-native';
const PressableExample = () => {
return (
<View style={styles.container}>
<Pressable
onPress={() => Alert.alert('Pressable', 'Standard press!')}
onLongPress={() => Alert.alert('Pressable', 'Long press!')}
// The `style` prop can be a function to change style based on pressed state
style={({ pressed }) => [
styles.pressableButton,
{ backgroundColor: pressed ? 'rgb(210, 230, 255)' : '#28a745' }
]}
// android_ripple={{ color: 'grey', borderless: false }}
// hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}
>
{({ pressed }) => (
<Text style={styles.buttonText}>
{pressed ? 'Pressed!' : 'Press Me (Pressable)'}
</Text>
)}
</Pressable>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1, justifyContent: 'center', alignItems: 'center', padding: 20
},
pressableButton: {
paddingVertical: 12,
paddingHorizontal: 25,
borderRadius: 8,
elevation: 3,
},
buttonText: {
color: 'white',
fontSize: 16,
fontWeight: 'bold',
textAlign: 'center',
}
});
export default PressableExample;

Pressable offre des fonctionnalités telles que :

  • onPressIn, onPressOut, onLongPress.
  • Des props style et children fonctionnelles pour changer dynamiquement en fonction de l’état d’interaction (pressed).
  • android_ripple pour l’effet d’ondulation d’Android.
  • hitSlop pour étendre la zone tactile sans modifier la mise en page.

TouchableNativeFeedback (Android uniquement)

Section titled “TouchableNativeFeedback (Android uniquement)”

Ce composant fournit l’effet d’ondulation natif d’Android. Il ne fonctionne que sur Android. Pour les solutions multiplateformes, Pressable avec android_ripple est préféré, ou utilisez TouchableOpacity pour une sensation cohérente.

// TouchableNativeFeedbackExample.js (Android Only)
import React from 'react';
import { View, TouchableNativeFeedback, Text, StyleSheet, Platform, Alert } from 'react-native';
const TouchableNativeFeedbackExample = () => {
if (Platform.OS === 'android') {
return (
<View style={styles.container}>
<TouchableNativeFeedback
onPress={() => Alert.alert('Native Feedback', 'Ripple effect!')}
background={TouchableNativeFeedback.Ripple('rgba(255,255,255,0.3)', false)} // color, borderless
useForeground={true} // Ripple effect on foreground, good for rounded corners
>
<View style={styles.nativeFeedbackButton}>
<Text style={styles.buttonText}>Button (Native Ripple)</Text>
</View>
</TouchableNativeFeedback>
</View>
);
}
return (
<View style={styles.container}><Text>TouchableNativeFeedback is Android-only.</Text></View>
);
};
// (Styles similar to other examples)
const styles = StyleSheet.create({
container: { flex: 1, justifyContent: 'center', alignItems: 'center', padding: 20 },
nativeFeedbackButton: { backgroundColor: '#ffc107', paddingVertical: 12, paddingHorizontal: 25, borderRadius: 8, alignItems: 'center', justifyContent: 'center' },
buttonText: { color: '#212529', fontSize: 16, fontWeight: 'bold' }
});
export default TouchableNativeFeedbackExample;

Ce composant gère les événements tactiles mais ne fournit aucun retour visuel. Il est utile pour créer des interactions tactiles personnalisées où le retour par défaut n’est pas souhaité.

// TouchableWithoutFeedbackExample.js
import React from 'react';
import { View, TouchableWithoutFeedback, Text, StyleSheet, Alert } from 'react-native';
const TouchableWithoutFeedbackExample = () => {
return (
<View style={styles.container}>
<TouchableWithoutFeedback onPress={() => Alert.alert('No Feedback', 'Touched!')}>
<View style={styles.noFeedbackView}>
<Text>Touch Area (No Visual Feedback)</Text>
</View>
</TouchableWithoutFeedback>
</View>
);
};
const styles = StyleSheet.create({
container: { flex: 1, justifyContent: 'center', alignItems: 'center' },
noFeedbackView: { padding: 20, backgroundColor: '#e9ecef', borderWidth: 1, borderColor: '#ced4da' }
});
export default TouchableWithoutFeedbackExample;

Choisir le bon composant tactile dépend de l’expérience utilisateur souhaitée et du niveau de personnalisation. Pressable est souvent le meilleur choix polyvalent pour les nouveaux développements. En savoir plus sur : https://reactnative.dev/docs/handling-touches