{"id":3967,"date":"2023-11-04T23:13:57","date_gmt":"2023-11-04T23:13:57","guid":{"rendered":"http:\/\/localhost:10003\/getting-started-with-react-native\/"},"modified":"2023-11-05T05:48:27","modified_gmt":"2023-11-05T05:48:27","slug":"getting-started-with-react-native","status":"publish","type":"post","link":"http:\/\/localhost:10003\/getting-started-with-react-native\/","title":{"rendered":"Getting Started with React Native"},"content":{"rendered":"
React Native offers developers the ability to build mobile applications using the same technologies used for web development. It allows developers to create cross-platform mobile apps while reusing as much code as possible, reducing development time and effort. In this tutorial, we’ll walk through the basics of getting started with React Native and building a simple mobile application.<\/p>\n
Before we begin, we’ll need to make sure that we have a few things set up and ready to go. These include:<\/p>\n
An IDE or text editor \u2013 This can be any text editor or IDE of your choice, though we recommend using Visual Studio Code or Atom.<\/p>\n<\/li>\n
A mobile device or emulator \u2013 We’ll need to have a mobile device or emulator set up in order to run our application. We recommend using either an Android emulator or the iOS Simulator that comes with Xcode.<\/p>\n<\/li>\n<\/ol>\n
Let’s start by creating a new React Native project. Open up your terminal and navigate to the directory where you want to create your project. Then, type the following command to initialize a new React Native project:<\/p>\n
npx react-native init MyProject\n<\/code><\/pre>\nThis will create a new React Native project named MyProject<\/code> in the directory that you’re currently in. Once the project has been created, navigate into the newly created directory by typing:<\/p>\ncd MyProject\n<\/code><\/pre>\nNext, we’ll need to start up the React Native development server. In your terminal, run the following command:<\/p>\n
npx react-native start\n<\/code><\/pre>\nThis will start up the development server and open up a Metro Bundler page in your browser. The Metro Bundler page displays a list of all the JavaScript modules that have been loaded into your application, as well as any errors that may have occurred during the build process.<\/p>\n
Now that the development server is up and running, we can start our mobile application. Open up a new terminal window and navigate to the root directory of your React Native project. Then, run the following command:<\/p>\n
npx react-native run-ios\n<\/code><\/pre>\nThis command will start up the iOS Simulator and install your application on it. If you prefer to use an Android emulator instead, simply run the command npx react-native run-android<\/code> instead.<\/p>\nCongratulations! You’ve just run your first React Native application. The default React Native project will open in the mobile emulator or device.<\/p>\n
Exploring the Code<\/h2>\n
Now that we have a basic application up and running, let’s take a look at the basic structure of a React Native project.<\/p>\n
App.js<\/h3>\n
The App.js<\/code> file is the backbone of any React Native project. It’s where you’ll find the root component of your application, which is responsible for rendering all of the other components within your app. By default, the App.js<\/code> file contains a simple “Hello, world!” message.<\/p>\nimport React from 'react';\nimport { StyleSheet, Text, View } from 'react-native';\n\nexport default function App() {\n return (\n <View style={styles.container}>\n <Text>Hello, world!<\/Text>\n <\/View>\n );\n}\n\nconst styles = StyleSheet.create({\n container: {\n flex: 1,\n backgroundColor: '#fff',\n alignItems: 'center',\n justifyContent: 'center',\n },\n});\n<\/code><\/pre>\nindex.js<\/h3>\n
The index.js<\/code> file is the entry point for your React Native application. It’s responsible for registering the root component of your application and rendering it to the mobile device or emulator.<\/p>\nimport { AppRegistry } from 'react-native';\nimport App from '.\/App';\nimport { name as appName } from '.\/app.json';\n\nAppRegistry.registerComponent(appName, () => App);\n<\/code><\/pre>\npackage.json<\/h3>\n
The package.json<\/code> file contains information about your React Native project, including the name, version, and dependencies. You can view and manage your dependencies by running npm install<\/code> in your project directory.<\/p>\n{\n \"name\": \"MyProject\",\n \"version\": \"0.0.1\",\n \"private\": true,\n \"scripts\": {\n \"android\": \"react-native run-android\",\n \"ios\": \"react-native run-ios\",\n \"start\": \"react-native start\",\n \"test\": \"jest\"\n },\n \"dependencies\": {\n \"@react-native-community\/masked-view\": \"^0.1.10\",\n \"@react-navigation\/native\": \"^5.7.3\",\n \"@react-navigation\/stack\": \"^5.9.0\",\n \"react\": \"16.13.1\",\n \"react-native\": \"0.63.2\",\n \"react-native-gesture-handler\": \"^1.8.0\",\n \"react-native-reanimated\": \"^1.13.0\",\n \"react-native-safe-area-context\": \"^3.1.8\",\n \"react-native-screens\": \"^2.10.1\"\n },\n \"devDependencies\": {\n \"@babel\/core\": \"^7.11.6\",\n \"@babel\/runtime\": \"^7.11.2\",\n \"@react-native-community\/eslint-config\": \"^1.1.0\",\n \"babel-jest\": \"^26.3.0\",\n \"eslint\": \"^7.10.0\",\n \"jest\": \"^26.4.2\",\n \"metro-react-native-babel-preset\": \"^0.63.0\",\n \"react-test-renderer\": \"16.13.1\"\n },\n \"jest\": {\n \"preset\": \"react-native\"\n }\n}\n<\/code><\/pre>\nBuilding a Basic User Interface<\/h2>\n
Now that we have a basic understanding of React Native and how to set up a new project, let’s build a simple user interface. For this tutorial, we’ll create a simple shopping list application that allows users to add items to their list.<\/p>\n
Creating a New Component<\/h3>\n
To get started, let’s create a new component that will display our shopping list. Create a new file called ShoppingList.js<\/code> in your src<\/code> directory and add the following code:<\/p>\nimport React from 'react';\nimport { StyleSheet, Text, View } from 'react-native';\n\nexport default function ShoppingList() {\n return (\n <View style={styles.container}>\n <Text style={styles.title}>Shopping List<\/Text>\n <\/View>\n );\n}\n\nconst styles = StyleSheet.create({\n container: {\n flex: 1,\n paddingTop: 40,\n paddingHorizontal: 20,\n backgroundColor: '#fff',\n },\n title: {\n fontSize: 32,\n fontWeight: 'bold',\n marginBottom: 20,\n },\n});\n<\/code><\/pre>\nThe ShoppingList<\/code> component is a simple functional component that returns a View<\/code> component containing a Text<\/code> component displaying the title of our shopping list. It also includes some basic styles to set the background color, font size, and spacing.<\/p>\nUsing the Component in App.js<\/h3>\n
Now that we have our ShoppingList<\/code> component, let’s use it in our App.js<\/code> file. Modify the App<\/code> function to look like this:<\/p>\nexport default function App() {\n return (\n <View style={styles.container}>\n <ShoppingList \/>\n <\/View>\n );\n}\n<\/code><\/pre>\nThis will render the ShoppingList<\/code> component within our View<\/code> container.<\/p>\nAdding a Form to Add Items<\/h3>\n
Now that we have the basic structure of our shopping list, let’s add a form that will allow us to add new items. Create a new file called AddItem.js<\/code> in your src<\/code> directory and add the following code:<\/p>\nimport React, { useState } from 'react';\nimport { StyleSheet, Text, TextInput, TouchableOpacity, View } from 'react-native';\nimport { AntDesign } from '@expo\/vector-icons';\n\nexport default function AddItem({ addItem }) {\n const [text, setText] = useState('');\n\n const handleChange = (value) => {\n setText(value);\n };\n\n const handleSubmit = () => {\n addItem(text);\n setText('');\n };\n\n return (\n <View style={styles.container}>\n <TextInput\n style={styles.input}\n placeholder=\"Add Item...\"\n value={text}\n onChangeText={handleChange}\n \/>\n <TouchableOpacity style={styles.buttonContainer} onPress={handleSubmit}>\n <AntDesign name=\"plus\" size={24} color=\"white\" \/>\n <Text style={styles.buttonText}>Add<\/Text>\n <\/TouchableOpacity>\n <\/View>\n );\n}\n\nconst styles = StyleSheet.create({\n container: {\n flexDirection: 'row',\n justifyContent: 'space-between',\n alignContent: 'center',\n marginHorizontal: 20,\n marginVertical: 10,\n },\n input: {\n height: 40,\n borderColor: '#ccc',\n borderWidth: 1,\n borderRadius: 5,\n paddingHorizontal: 10,\n marginRight: 5,\n flex: 1,\n },\n buttonContainer: {\n flexDirection: 'row',\n justifyContent: 'center',\n alignItems: 'center',\n backgroundColor: '#000',\n borderRadius: 5,\n paddingHorizontal: 10,\n },\n buttonText: {\n color: '#fff',\n marginLeft: 5,\n fontSize: 16,\n },\n});\n<\/code><\/pre>\nThe AddItem<\/code> component is a functional component that takes in a prop called addItem<\/code>. This prop is a function that will be called when the user adds a new item to the shopping list.<\/p>\nThe component contains a TextInput<\/code> component and a TouchableOpacity<\/code> component. The TextInput<\/code> component allows users to input the name of the item they want to add, and the TouchableOpacity<\/code> component is a button that they can press to add the item to the list.<\/p>\nUsing the AddItem Component in ShoppingList.js<\/h3>\n
Now that we have our AddItem<\/code> component, let’s use it in our ShoppingList<\/code> component. Add the following code to the bottom of the ShoppingList<\/code> function:<\/p>\nconst handleAddItem = (text) => {\n console.log(text);\n};\n\nreturn (\n <View style={styles.container}>\n <Text style={styles.title}>Shopping List<\/Text>\n <AddItem addItem={handleAddItem} \/>\n <\/View>\n);\n<\/code><\/pre>\nThis will display the AddItem<\/code> component below the title of our shopping list. The handleAddItem<\/code> function simply logs the text that’s passed in to the console for now, but we’ll update it later to actually add the item to our list.<\/p>\nManaging State to Update the UI<\/h2>\n
Now that we have our basic application structure in place, let’s focus on managing state in order to update our UI as the user interacts with it.<\/p>\n
Updating handleAddItem to Change State<\/h3>\n
Currently, our handleAddItem<\/code> function simply logs the text that’s passed in to the console. Let’s update it to actually add the item to our list.<\/p>\nconst [items, setItems] = useState([]);\n\nconst handleAddItem = (text) => {\n setItems((prevItems) => [\n ...prevItems,\n { id: Math.random().toString(), text },\n ]);\n};\n<\/code><\/pre>\nThis creates a new state variable called items<\/code> that’s an empty array by default. The handleAddItem<\/code> function takes in the text<\/code> value that’s passed in from the AddItem<\/code> component and adds a new item to the items<\/code> array. The new item is an object with an id<\/code> property (which is a randomly generated string) and a text<\/code> property (which contains the value of the text<\/code> variable).<\/p>\nDisplaying the List of Items<\/h3>\n
Now that we’re adding items to our list, we need to display them in our UI. We can do this by mapping over the items<\/code> array and rendering a Text<\/code> component for each one.<\/p>\n<View style={styles.container}>\n <Text style={styles.title}>Shopping List<\/Text>\n <AddItem addItem={handleAddItem} \/>\n {items.map((item) => (\n <Text key={item.id}>{item.text}<\/Text>\n ))}\n<\/View>\n<\/code><\/pre>\nThis will render each item in our items<\/code> array as a Text<\/code> component with the text<\/code> value of the item.<\/p>\nAdding the ability to delete items<\/h3>\n
Now that we have the ability to display our list of items, let’s add the ability to delete items when the user is done with them. We can do this by adding a delete button to each item that will remove it from the items<\/code> array.<\/p>\n<View style={styles.container}>\n <Text style={styles.title}>Shopping List<\/Text>\n <AddItem addItem={handleAddItem} \/>\n {items.map((item) => (\n <View key={item.id} style={styles.item}>\n <Text style={styles.itemText}>{item.text}<\/Text>\n <TouchableOpacity\n style={styles.deleteButton}\n onPress={() =>\n setItems((prevItems) =>\n prevItems.filter((prevItem) => prevItem.id !== item.id)\n )\n }\n >\n <Text style={styles.deleteButtonText}>Delete<\/Text>\n <\/TouchableOpacity>\n <\/View>\n ))}\n<\/View>\n<\/code><\/pre>\nThis code adds a new property to each item object called id<\/code>. We also render each item as a new component called Item<\/code>, which contains the Text<\/code> component displaying the text<\/code> value of the item as well as a TouchableOpacity<\/code> component that triggers the setItems<\/code> function with a new array of items that excludes the item with the ID that matches the current item’s ID.<\/p>\nFinal Code<\/h3>\n
Here’s the completed code for our simple shopping list application:<\/p>\n
import React, { useState } from 'react';\nimport { StyleSheet, Text, TextInput, TouchableOpacity, View } from 'react-native';\nimport { AntDesign } from '@expo\/vector-icons';\n\nexport default function App() {\n const [items, setItems] = useState([]);\n\n const handleAddItem = (text) => {\n setItems((prevItems) => [\n ...prevItems,\n { id: Math.random().toString(), text },\n ]);\n };\n\n return (\n <View style={styles.container}>\n <Text style={styles.title}>Shopping List<\/Text>\n <AddItem addItem={handleAddItem} \/>\n {items.map((item) => (\n <View key={item.id} style={styles.item}>\n <Text style={styles.itemText}>{item.text}<\/Text>\n <TouchableOpacity\n style={styles.deleteButton}\n onPress={() =>\n setItems((prevItems) =>\n prevItems.filter((prevItem) => prevItem.id !== item.id)\n )\n }\n >\n <Text style={styles.deleteButtonText}>Delete<\/Text>\n <\/TouchableOpacity>\n <\/View>\n ))}\n <\/View>\n );\n}\n\nfunction AddItem({ addItem }) {\n const [text, setText] = useState('');\n\n const handleChange = (value) => {\n setText(value);\n };\n\n const handleSubmit = () => {\n addItem(text);\n setText('');\n };\n\n return (\n <View style={styles.container}>\n <TextInput\n style={styles.input}\n placeholder=\"Add Item...\"\n value={text}\n onChangeText={handleChange}\n \/>\n <TouchableOpacity style={styles.buttonContainer} onPress={handleSubmit}>\n <AntDesign name=\"plus\" size={24} color=\"white\" \/>\n <Text style={styles.buttonText}>Add<\/Text>\n <\/TouchableOpacity>\n <\/View>\n );\n}\n\nconst styles = StyleSheet.create({\n container: {\n flex: 1,\n paddingTop: 40,\n paddingHorizontal: 20,\n backgroundColor: '#fff',\n },\n title: {\n fontSize: 32,\n fontWeight: 'bold',\n marginBottom: 20,\n },\n item: {\n flexDirection: 'row',\n justifyContent: 'space-between',\n alignItems: 'center',\n borderColor: '#ccc',\n borderWidth: 1,\n borderRadius: 5,\n paddingHorizontal: 10,\n paddingVertical: 10,\n marginVertical: 5,\n },\n itemText: {\n fontSize: 18,\n },\n deleteButton: {\n backgroundColor: '#ff0000',\n borderRadius: 5,\n paddingHorizontal: 10,\n paddingVertical: 5,\n },\n deleteButtonText: {\n color: '#fff',\n },\n input: {\n height: 40,\n borderColor: '#ccc',\n borderWidth: 1,\n borderRadius: 5,\n paddingHorizontal: 10,\n marginRight: 5,\n flex: 1,\n },\n buttonContainer: {\n flexDirection: 'row',\n justifyContent: 'center',\n alignItems: 'center',\n backgroundColor: '#000',\n borderRadius: 5,\n paddingHorizontal: 10,\n },\n buttonText: {\n color: '#fff',\n marginLeft: 5,\n fontSize: 16,\n },\n});\n<\/code><\/pre>\nConclusion<\/h2>\n
In this tutorial, we covered the basics of getting started with React Native, including setting up a new project, creating components, managing state, and updating the UI. By following this tutorial, you should now have a better understanding of how to build mobile applications using React Native. With this knowledge, you can continue to build more complex applications and explore the vast array of libraries and tools available for React Native development.<\/p>\n","protected":false},"excerpt":{"rendered":"
React Native offers developers the ability to build mobile applications using the same technologies used for web development. It allows developers to create cross-platform mobile apps while reusing as much code as possible, reducing development time and effort. In this tutorial, we’ll walk through the basics of getting started with Continue Reading<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_import_markdown_pro_load_document_selector":0,"_import_markdown_pro_submit_text_textarea":"","footnotes":""},"categories":[1],"tags":[606,425,156,9,605],"yoast_head":"\nGetting Started with React Native - Pantherax Blogs<\/title>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\n\t\n\t\n