How to Use Button in React Native: Simple Guide
Button component by importing it from 'react-native' and adding it to your JSX with properties like title for the button text and onPress for the action when pressed. This creates a simple clickable button that triggers a function when tapped.Syntax
The Button component requires at least two props: title which sets the text shown on the button, and onPress which is a function called when the button is tapped. You can also customize the button color with the color prop.
import React from 'react'; import { Button } from 'react-native'; export default function App() { return ( <Button title="Press me" onPress={() => alert('Button pressed!')} color="#007AFF" /> ); }
Example
This example shows a complete React Native app with a button that displays an alert when pressed. It demonstrates how to import, use the Button component, and handle the press event.
import React from 'react'; import { View, Button, Alert, StyleSheet } from 'react-native'; export default function App() { return ( <View style={styles.container}> <Button title="Click me" onPress={() => Alert.alert('You clicked the button!')} color="#2196F3" /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#fff' } });
Common Pitfalls
Common mistakes include forgetting to provide the onPress prop, which makes the button unresponsive, or passing a function call instead of a function reference (e.g., onPress={alert('Hi')} runs immediately instead of on press). Also, the Button component has limited styling options, so for custom styles use TouchableOpacity or other components.
/* Wrong: onPress runs immediately */ <Button title="Wrong" onPress={alert('Hi')} /> /* Right: onPress is a function reference */ <Button title="Right" onPress={() => alert('Hi')} />
Quick Reference
| Prop | Description | Type | Default |
|---|---|---|---|
| title | Text shown on the button | string | Required |
| onPress | Function called when button is pressed | function | Required |
| color | Button text color (iOS) or background color (Android) | string | Platform default |
| disabled | Disables the button if true | boolean | false |
| testID | Used for testing automation | string | undefined |