React Native Button Component
The following approach covers how to use the Button in react-native. For this, we are going to use the Button component. It is basically a clickable component which is used to perform some action when clicked by the user.
Syntax:
<Button onPress={} title="Button" color="#841584" />
Props in Button:
- onPress: It is called when the user tap on the button.
- title: It is the text which displays inside the button.
- accessibilityLabel: Text to display for blindness accessibility features.
- color: It is used to set the color of the button.
- disabled: If it is true, then user didn’t able to press the button.
- hasTVPreferredFocus: TV preferred focus, It is only available for TV.
- nextFocusDown: Designates the next view to receive focus when the user navigates down.
- nextFocusForward: Designates the next view to receive focus when the user navigates forward.
- nextFocusLeft: Designates the next view to receive focus when the user navigates left.
- nextFocusRight: Designates the next view to receive focus when the user navigates right.
- nextFocusUp: Designates the next view to receive focus when the user navigates up.
- testID: It is used to locate this view in end-to-end tests.
- touchSoundDisabled: If true, doesn’t play system sound on touch.
Now let’s start with the implementation:
-
Step 1: Open your terminal and install expo-cli by the following command.
npm install -g expo-cli
-
Step 2: Now create a project by the following command.
expo init myapp
-
Step 3: Now go into your project folder i.e. myapp
cd myapp
Project Structure: It will look like the following.
Example: Now lets implement the Button. Here we created a Button and when someone clicks on that button the count will change.
App.js
App.js
import React , {useState} from 'react' ; import { StyleSheet, Text, View , Button } from 'react-native' ; export default function App() { const [count , setcount] = useState(0); const changeCount = () => { setcount(count + 1); } return ( <View style={styles.container}> <Text style={styles.text}>{count}</Text> <Button title={ "Click Me" } onPress={changeCount} /> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff' , alignItems: 'center' , justifyContent: 'center' , }, text : { fontSize : 40, marginBottom : 30 } }); |
Start the server by using the following command.
npm run android
Output: If your emulator did not open automatically then you need to do it manually. First, go to your android studio and run the emulator. Now start the server again.
Reference: https://reactnative.dev/docs/button