React Native – Status Bar

React Native – Status Bar ”; Previous Next In this chapter, we will show you how to control the status bar appearance in React Native. The Status bar is easy to use and all you need to do is set properties to change it. The hidden property can be used to hide the status bar. In our example it is set to false. This is default value. The barStyle can have three values – dark-content, light-content and default. This component has several other properties that can be used. Some of them are Android or IOS specific. You can check it in official documentation. App.js import React, { Component } from ”react”; import { StatusBar } from ”react-native” const App = () => { return ( <StatusBar barStyle = “dark-content” hidden = {false} backgroundColor = “#00BCD4″ translucent = {true}/> ) } export default App If we run the app, the status bar will be visible and content will have dark color. Output Print Page Previous Next Advertisements ”;

React Native – Environment Setup

React Native – Environment Setup ”; Previous Next There are a couple of things you need to install to set up the environment for React Native. We will use OSX as our building platform. Sr.No. Software Description 1 NodeJS and NPM You can follow our NodeJS Environment Setup tutorial to install NodeJS. Step 1: Install create-react-native-app After installing NodeJS and NPM successfully in your system you can proceed with installation of create-react-native-app (globally as shown below). C:UsersTutorialspoint> npm install -g create-react-native-app Step 2: Create project Browse through required folder and create a new react native project as shown below. C:UsersTutorialspoint>cd Desktop C:UsersTutorialspointDesktop>create-react-native-app MyReactNative After executing the above command, a folder with specifies name is created with the following contents. Step 3: NodeJS Python Jdk8 Make sure you have Python NodeJS and jdk8 installed in your system if not, install them. In addition to these it is recommended to install latest version of yarn to avoid certain issues. Step 4: Install React Native CLI You can install react native command line interface on npm, using the install -g react-native-cli command as shown below. npm install -g react-native-cli Step 5: Start react native To verify the installation browse through the project folder and try starting the project using the start command. C:UsersTutorialspointDesktop>cd MyReactNative C:UsersTutorialspointDesktopMyReactNative>npm start If everything went well you will get a QR code as shown below. As instructed, one way to run react native apps on your android devise is to using expo. Install expo client in your android devise and scan the above obtained QR code. Step 6: Eject the project If you want to run android emulator using android studio, come out of the current command line by pressing ctrl+c. Then, execute run eject command as npm run eject This prompts you options to eject, select the first one using arrows and press enter. Then, you should suggest the name of the app on home screen and project name of the Android studio and Xcode projects. Though your project ejected successfully, you may get an error as − Ignore this error and run react native for android using the following command − react-native run-android But, before that you need to install android studio. Step 7: Installing Android Studio Visit the web page https://developer.android.com/studio/ and download android studio. After downloading the installation file of it, double click on it and proceed with the installation. Step 8: Configuring AVD Manager To configure the AVD Manager click on the respective icon in the menu bar. Step 9: Configuring AVD Manager Choose a device definition, Nexus 5X is suggestable. Click on the Next button you will see a System Image window. Select the x86 Images tab. Then, select Marshmallow and click on next. Finally, click on the Finish button to finish the AVD configuration. After configuring your virtual device click on the play button under the Actions column to start your android emulator. Step 10: Running android Open command prompt, browse through your project folder and, execute the react-native run-android command. Then, your app execution begins in another prompt you can see its status. In your android emulator you can see the execution of the default app as − Step 11: local.properties Open the android folder in your project folder SampleReactNative/android (in this case). Create a file with named local.properties and add the following path in it. sdk.dir = /C:\Users\Tutorialspoint\AppData\Local\Android\Sdk here, replace Tutorialspoint with your user name. Step 12: Hot Reloading And to build application modify the App.js and the changes will be automatically updated on the android emulator. If not, click on the android emulator press ctrl+m then, select Enable Hot Reloading option. Print Page Previous Next Advertisements ”;

React Native – HTTP

React Native – HTTP ”; Previous Next In this chapter, we will show you how to use fetch for handling network requests. App.js import React from ”react”; import HttpExample from ”./http_example.js” const App = () => { return ( <HttpExample /> ) } export default App Using Fetch We will use the componentDidMount lifecycle method to load the data from server as soon as the component is mounted. This function will send GET request to the server, return JSON data, log output to console and update our state. http_example.js import React, { Component } from ”react” import { View, Text } from ”react-native” class HttpExample extends Component { state = { data: ”” } componentDidMount = () => { fetch(”https://jsonplaceholder.typicode.com/posts/1”, { method: ”GET” }) .then((response) => response.json()) .then((responseJson) => { console.log(responseJson); this.setState({ data: responseJson }) }) .catch((error) => { console.error(error); }); } render() { return ( <View> <Text> {this.state.data.body} </Text> </View> ) } } export default HttpExample Output Print Page Previous Next Advertisements ”;

React Native – AsyncStorage

React Native – AsyncStorage ”; Previous Next In this chapter, we will show you how to persist your data using AsyncStorage. Step 1: Presentation In this step, we will create the App.js file. import React from ”react” import AsyncStorageExample from ”./async_storage_example.js” const App = () => { return ( <AsyncStorageExample /> ) } export default App Step 2: Logic Name from the initial state is empty string. We will update it from persistent storage when the component is mounted. setName will take the text from our input field, save it using AsyncStorage and update the state. async_storage_example.js import React, { Component } from ”react” import { StatusBar } from ”react-native” import { AsyncStorage, Text, View, TextInput, StyleSheet } from ”react-native” class AsyncStorageExample extends Component { state = { ”name”: ”” } componentDidMount = () => AsyncStorage.getItem(”name”).then((value) => this.setState({ ”name”: value })) setName = (value) => { AsyncStorage.setItem(”name”, value); this.setState({ ”name”: value }); } render() { return ( <View style = {styles.container}> <TextInput style = {styles.textInput} autoCapitalize = ”none” onChangeText = {this.setName}/> <Text> {this.state.name} </Text> </View> ) } } export default AsyncStorageExample const styles = StyleSheet.create ({ container: { flex: 1, alignItems: ”center”, marginTop: 50 }, textInput: { margin: 5, height: 100, borderWidth: 1, backgroundColor: ”#7685ed” } }) When we run the app, we can update the text by typing into the input field. Print Page Previous Next Advertisements ”;

React Native – ListView

React Native – ListView ”; Previous Next In this chapter, we will show you how to create a list in React Native. We will import List in our Home component and show it on screen. App.js import React from ”react” import List from ”./List.js” const App = () => { return ( <List /> ) } export default App To create a list, we will use the map() method. This will iterate over an array of items, and render each one. List.js import React, { Component } from ”react” import { Text, View, TouchableOpacity, StyleSheet } from ”react-native” class List extends Component { state = { names: [ { id: 0, name: ”Ben”, }, { id: 1, name: ”Susan”, }, { id: 2, name: ”Robert”, }, { id: 3, name: ”Mary”, } ] } alertItemName = (item) => { alert(item.name) } render() { return ( <View> { this.state.names.map((item, index) => ( <TouchableOpacity key = {item.id} style = {styles.container} onPress = {() => this.alertItemName(item)}> <Text style = {styles.text}> {item.name} </Text> </TouchableOpacity> )) } </View> ) } } export default List const styles = StyleSheet.create ({ container: { padding: 10, marginTop: 3, backgroundColor: ”#d9f9b1”, alignItems: ”center”, }, text: { color: ”#4f603c” } }) When we run the app, we will see the list of names. You can click on each item in the list to trigger an alert with the name. Print Page Previous Next Advertisements ”;

React Native – Quick Guide

React Native – Quick Guide ”; Previous Next React Native – Overview For better understanding of React Native concepts, we will borrow a few lines from the official documentation − React Native lets you build mobile apps using only JavaScript. It uses the same design as React, letting you compose a rich mobile UI from declarative components. With React Native, you don”t build a mobile web app, an HTML5 app, or a hybrid app; you build a real mobile app that”s indistinguishable from an app built using Objective-C or Java. React Native uses the same fundamental UI building blocks as regular iOS and Android apps. You just put those building blocks together using JavaScript and React. React Native Features Following are the features of React Native − React − This is a Framework for building web and mobile apps using JavaScript. Native − You can use native components controlled by JavaScript. Platforms − React Native supports IOS and Android platform. React Native Advantages Follow are the advantages of React Native − JavaScript − You can use the existing JavaScript knowledge to build native mobile apps. Code sharing − You can share most of your code on different platforms. Community − The community around React and React Native is large, and you will be able to find any answer you need. React Native Limitations Following are the limitations of React Native − Native Components − If you want to create native functionality which is not created yet, you will need to write some platform specific code. React Native – Environment Setup There are a couple of things you need to install to set up the environment for React Native. We will use OSX as our building platform. Sr.No. Software Description 1 NodeJS and NPM You can follow our NodeJS Environment Setup tutorial to install NodeJS. Step 1: Install create-react-native-app After installing NodeJS and NPM successfully in your system you can proceed with installation of create-react-native-app (globally as shown below). C:UsersTutorialspoint> npm install -g create-react-native-app Step 2: Create project Browse through required folder and create a new react native project as shown below. C:UsersTutorialspoint>cd Desktop C:UsersTutorialspointDesktop>create-react-native-app MyReactNative After executing the above command, a folder with specifies name is created with the following contents. Step 3: NodeJS Python Jdk8 Make sure you have Python NodeJS and jdk8 installed in your system if not, install them. In addition to these it is recommended to install latest version of yarn to avoid certain issues. Step 4: Install React Native CLI You can install react native command line interface on npm, using the install -g react-native-cli command as shown below. npm install -g react-native-cli Step 5: Start react native To verify the installation browse through the project folder and try starting the project using the start command. C:UsersTutorialspointDesktop>cd MyReactNative C:UsersTutorialspointDesktopMyReactNative>npm start If everything went well you will get a QR code as shown below. As instructed, one way to run react native apps on your android devise is to using expo. Install expo client in your android devise and scan the above obtained QR code. Step 6: Eject the project If you want to run android emulator using android studio, come out of the current command line by pressing ctrl+c. Then, execute run eject command as npm run eject This prompts you options to eject, select the first one using arrows and press enter. Then, you should suggest the name of the app on home screen and project name of the Android studio and Xcode projects. Though your project ejected successfully, you may get an error as − Ignore this error and run react native for android using the following command − react-native run-android But, before that you need to install android studio. Step 7: Installing Android Studio Visit the web page https://developer.android.com/studio/ and download android studio. After downloading the installation file of it, double click on it and proceed with the installation. Step 8: Configuring AVD Manager To configure the AVD Manager click on the respective icon in the menu bar. Step 9: Configuring AVD Manager Choose a device definition, Nexus 5X is suggestable. Click on the Next button you will see a System Image window. Select the x86 Images tab. Then, select Marshmallow and click on next. Finally, click on the Finish button to finish the AVD configuration. After configuring your virtual device click on the play button under the Actions column to start your android emulator. Step 10: Running android Open command prompt, browse through your project folder and, execute the react-native run-android command. Then, your app execution begins in another prompt you can see its status. In your android emulator you can see the execution of the default app as − Step 11: local.properties Open the android folder in your project folder SampleReactNative/android (in this case). Create a file with named local.properties and add the following path in it. sdk.dir = /C:\Users\Tutorialspoint\AppData\Local\Android\Sdk here, replace Tutorialspoint with your user name. Step 12: Hot Reloading And to build application modify the App.js and the changes will be automatically updated on the android emulator. If not, click on the android emulator press ctrl+m then, select Enable Hot Reloading option. React Native – App If you open the default app you can observe that the app.js file looks like import React from ”react”; import { StyleSheet, Text, View } from ”react-native”; export default class App extends React.Component { render() { return ( <View style = {styles.container}> <Text>Open up App.js to start working on your app!</Text> <Text>Changes you make will automatically reload.</Text> <Text>Shake your phone to open the developer menu.</Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: ”#fff”, alignItems: ”center”, justifyContent: ”center”, }, }); Output Hello world To display a simple message saying “Welcome to Tutorialspoint” remove the CSS part and insert the message to be printed wrapped by the <text></text> tags inside <view></view> as shown below. import React from ”react”; import { StyleSheet, Text, View } from ”react-native”; export default class App extends React.Component { render()

React Native – Alert

React Native – Alert ”; Previous Next In this chapter, we will understand how to create custom Alert component. Step 1: App.js import React from ”react” import AlertExample from ”./alert_example.js” const App = () => { return ( <AlertExample /> ) } export default App Step 2: alert_example.js We will create a button for triggering the showAlert function. import React from ”react” import { Alert, Text, TouchableOpacity, StyleSheet } from ”react-native” const AlertExample = () => { const showAlert = () =>{ Alert.alert( ”You need to…” ) } return ( <TouchableOpacity onPress = {showAlert} style = {styles.button}> <Text>Alert</Text> </TouchableOpacity> ) } export default AlertExample const styles = StyleSheet.create ({ button: { backgroundColor: ”#4ba37b”, width: 100, borderRadius: 50, alignItems: ”center”, marginTop: 100 } }) Output When you click the button, you will see the following − Print Page Previous Next Advertisements ”;

React Native – Discussion

Discuss React Native ”; Previous Next React Native is a JavaScript framework for building native mobile apps. It uses the React framework and offers large amount of inbuilt components and APIs. Print Page Previous Next Advertisements ”;

React Native – Buttons

React Native – Buttons ”; Previous Next In this chapter, we will show you touchable components in react Native. We call them ”touchable” because they offer built in animations and we can use the onPress prop for handling touch event. Facebook offers the Button component, which can be used as a generic button. Consider the following example to understand the same. App.js import React, { Component } from ”react” import { Button } from ”react-native” const App = () => { const handlePress = () => false return ( <Button onPress = {handlePress} title = “Red button!” color = “red” /> ) } export default App If the default Button component does not suit your needs, you can use one of the following components instead. Touchable Opacity This element will change the opacity of an element when touched. App.js import React from ”react” import { TouchableOpacity, StyleSheet, View, Text } from ”react-native” const App = () => { return ( <View style = {styles.container}> <TouchableOpacity> <Text style = {styles.text}> Button </Text> </TouchableOpacity> </View> ) } export default App const styles = StyleSheet.create ({ container: { alignItems: ”center”, }, text: { borderWidth: 1, padding: 25, borderColor: ”black”, backgroundColor: ”red” } }) Touchable Highlight When a user presses the element, it will get darker and the underlying color will show through. App.js import React from ”react” import { View, TouchableHighlight, Text, StyleSheet } from ”react-native” const App = (props) => { return ( <View style = {styles.container}> <TouchableHighlight> <Text style = {styles.text}> Button </Text> </TouchableHighlight> </View> ) } export default App const styles = StyleSheet.create ({ container: { alignItems: ”center”, }, text: { borderWidth: 1, padding: 25, borderColor: ”black”, backgroundColor: ”red” } }) Touchable Native Feedback This will simulate ink animation when the element is pressed. App.js import React from ”react” import { View, TouchableNativeFeedback, Text, StyleSheet } from ”react-native” const Home = (props) => { return ( <View style = {styles.container}> <TouchableNativeFeedback> <Text style = {styles.text}> Button </Text> </TouchableNativeFeedback> </View> ) } export default Home const styles = StyleSheet.create ({ container: { alignItems: ”center”, }, text: { borderWidth: 1, padding: 25, borderColor: ”black”, backgroundColor: ”red” } }) Touchable Without Feedback This should be used when you want to handle the touch event without any animation Usually, this component is not used much. <TouchableWithoutFeedback> <Text> Button </Text> </TouchableWithoutFeedback> Print Page Previous Next Advertisements ”;

React Native – Animations

React Native – Animations ”; Previous Next In this chapter, we will show you how to use LayoutAnimation in React Native. Animations Component We will set myStyle as a property of the state. This property is used for styling an element inside PresentationalAnimationComponent. We will also create two functions − expandElement and collapseElement. These functions will update values from the state. The first one will use the spring preset animation while the second one will have the linear preset. We will pass these as props too. The Expand and the Collapse buttons call the expandElement() and collapseElement() functions. In this example, we will dynamically change the width and the height of the box. Since the Home component will be the same, we will only change the Animations component. App.js import React, { Component } from ”react” import { View, StyleSheet, Animated, TouchableOpacity } from ”react-native” class Animations extends Component { componentWillMount = () => { this.animatedWidth = new Animated.Value(50) this.animatedHeight = new Animated.Value(100) } animatedBox = () => { Animated.timing(this.animatedWidth, { toValue: 200, duration: 1000 }).start() Animated.timing(this.animatedHeight, { toValue: 500, duration: 500 }).start() } render() { const animatedStyle = { width: this.animatedWidth, height: this.animatedHeight } return ( <TouchableOpacity style = {styles.container} onPress = {this.animatedBox}> <Animated.View style = {[styles.box, animatedStyle]}/> </TouchableOpacity> ) } } export default Animations const styles = StyleSheet.create({ container: { justifyContent: ”center”, alignItems: ”center” }, box: { backgroundColor: ”blue”, width: 50, height: 100 } }) Print Page Previous Next Advertisements ”;