![]() |
VOOZH | about |
The Button component in React Native is a simple and built-in UI element used to trigger actions when users tap it, making it essential for handling user interactions in mobile applications.
Syntax:
<Button
onPress={function...}
title="buttonText"
color="buttonColor"
/>These Button props in React Native provide control over appearance, behavior, accessibility, navigation, and testing of the Button component.
Controls how the button responds to user actions.
Defines the visual text and color of the button.
Improves usability for screen readers and assistive devices.
Improves usability for screen readers and assistive devices.
Helps identify the button during automated testing.
It involves using the React Native Button component to create interactive buttons that trigger actions and handle user input within an application.
Now, create a project with the following command.
npx create-expo-app app-name --templateNote: Replace the app-name with your app name for example : react-native-demo-app
Next, you might be asked to choose a template. Select one based on your preference as shown in the image below. I am selecting the blank template because it will generate a minimal app, as clean as an empty canvas in JavaScript.
It completes the project creation and displays a message: "Your Project is ready!" as shown in the image below.
Now go into your project folder, i.e., react-native-demo
cd app-nameStart the server by using the following command.
npx expo startThis will launch the Expo DevTools and display a QR code in the terminal and browser.
How to run the app:
Now let's implement the Button. Here we created a Button, and when someone clicks on that button, the count will change.
Import libraries: Import required libraries at the top of the file.
StyleSheet: Create a StyleSheet to style components like container, text.
Button: Create a button component and name it as "Click Me" to call a function that will increment the count value.
ChangeCount function: It is used to increment the count value by 1 and update the state i.e, count by calling setcount.
useState: It is used to declare a state variable 'count' with an initial value of 0 and a function 'setcount' to update it.
Text: It is used to represent the count coming from useState.
App Component: Wrap the Text and Button with a View and return that inside the App function to render and place the changeCount function and useState inside the App function, also make sure to export the App.
It brings together all the previously discussed parts into a single, complete App.js file that runs the application.
Output: