This tutorial aims to guide you through the initial steps of setting up and creating your first React Native app. By the end of this tutorial, you will have a basic understanding of React Native and its usage, along with a working app that you've built from scratch.
What you will learn:
Prerequisites:
Install Node.js and npm (Node Package Manager) from https://nodejs.org/. React Native uses Node for dependency management.
Install React Native CLI (Command Line Interface) globally using npm. In your terminal, type:
npm install -g react-native-cli
This will install the react-native command-line utility.
react-native init MyFirstApp
Replace "MyFirstApp" with the name you want for your application.
cd MyFirstApp
react-native run-ios
or
react-native run-android
Depending on the emulator you've installed. This will launch your app in the emulator.
You will see a welcome screen - congratulations, you have created your first React Native app!
Let's modify the default app to include a button that triggers an alert.
In App.js
, replace the content with:
import React from 'react';
import { Alert, Button, StyleSheet, View } from 'react-native';
export default function App() {
return (
<View style={styles.container}>
<Button title="Click Me" onPress={() => Alert.alert('Button Pressed!')} />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingHorizontal: 10,
},
});
In this code:
react-native
.Button
with the title "Click Me".onPress
prop to specify a function that gets called when the button is clicked. This function triggers an alert with the message "Button Pressed!".When you save and run this code, you should see a button in the center of the screen. When clicked, an alert pops up with the message "Button Pressed!".
In this tutorial, you've set up your development environment, created a new React Native app, and modified it to include a button and an alert. To learn more about React Native, you can explore its official documentation and try building more complex apps.
Solutions:
You can find solutions to these exercises (and more) in the official React Native documentation and various online resources. Don't hesitate to search for help when needed, and remember: practice makes perfect.
Keep coding, experimenting, and having fun with React Native!