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 ”;
Category: react Native
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 ”; 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 – 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 – Switch
React Native – Switch ”; Previous Next In this chapter, we will explain the Switch component in a couple of steps. Step 1: Create File We will use the HomeContainer component for logic, but we need to create the presentational component. Let us now create a new file: SwitchExample.js. Step 2: Logic We are passing value from the state and functions for toggling switch items to SwitchExample component. Toggle functions will be used for updating the state. App.js import React, { Component } from ”react” import { View } from ”react-native” import SwitchExample from ”./switch_example.js” export default class HomeContainer extends Component { constructor() { super(); this.state = { switch1Value: false, } } toggleSwitch1 = (value) => { this.setState({switch1Value: value}) console.log(”Switch 1 is: ” + value) } render() { return ( <View> <SwitchExample toggleSwitch1 = {this.toggleSwitch1} switch1Value = {this.state.switch1Value}/> </View> ); } } Step 3: Presentation Switch component takes two props. The onValueChange prop will trigger our toggle functions after a user presses the switch. The value prop is bound to the state of the HomeContainer component. switch_example.js import React, { Component } from ”react” import { View, Switch, StyleSheet } from ”react-native” export default SwitchExample = (props) => { return ( <View style = {styles.container}> <Switch onValueChange = {props.toggleSwitch1} value = {props.switch1Value}/> </View> ) } const styles = StyleSheet.create ({ container: { flex: 1, alignItems: ”center”, marginTop: 100 } }) If we press the switch, the state will be updated. You can check values in the console. Output Print Page Previous Next Advertisements ”;
React Native – Useful Resources ”; Previous Next The following resources contain additional information on React Native. Please use them to get more in-depth knowledge on this. Useful Links on React Native React Native − Website Reference for React Native Useful Books on React Native To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;
React Native – Modal
React Native – Modal ”; Previous Next In this chapter, we will show you how to use the modal component in React Native. Let us now create a new file: ModalExample.js We will put logic inside ModalExample. We can update the initial state by running the toggleModal. After updating the initial state by running the toggleModal, we will set the visible property to our modal. This prop will be updated when the state changes. The onRequestClose is required for Android devices. App.js import React, { Component } from ”react” import WebViewExample from ”./modal_example.js” const Home = () => { return ( <WebViewExample/> ) } export default Home; modal_example.js import React, { Component } from ”react”; import { Modal, Text, TouchableHighlight, View, StyleSheet} from ”react-native” class ModalExample extends Component { state = { modalVisible: false, } toggleModal(visible) { this.setState({ modalVisible: visible }); } render() { return ( <View style = {styles.container}> <Modal animationType = {“slide”} transparent = {false} visible = {this.state.modalVisible} onRequestClose = {() => { console.log(“Modal has been closed.”) } }> <View style = {styles.modal}> <Text style = {styles.text}>Modal is open!</Text> <TouchableHighlight onPress = {() => { this.toggleModal(!this.state.modalVisible)}}> <Text style = {styles.text}>Close Modal</Text> </TouchableHighlight> </View> </Modal> <TouchableHighlight onPress = {() => {this.toggleModal(true)}}> <Text style = {styles.text}>Open Modal</Text> </TouchableHighlight> </View> ) } } export default ModalExample const styles = StyleSheet.create ({ container: { alignItems: ”center”, backgroundColor: ”#ede3f2”, padding: 100 }, modal: { flex: 1, alignItems: ”center”, backgroundColor: ”#f7021a”, padding: 100 }, text: { color: ”#3f2949”, marginTop: 10 } }) Our starting screen will look like this − If we click the button, the modal will open. Print Page Previous Next Advertisements ”;
React Native – Images
React Native – Images ”; Previous Next In this chapter, we will understand how to work with images in React Native. Adding Image Let us create a new folder img inside the src folder. We will add our image (myImage.png) inside this folder. We will show images on the home screen. App.js import React from ”react”; import ImagesExample from ”./ImagesExample.js” const App = () => { return ( <ImagesExample /> ) } export default App Local image can be accessed using the following syntax. image_example.js import React, { Component } from ”react” import { Image } from ”react-native” const ImagesExample = () => ( <Image source = {require(”C:/Users/Tutorialspoint/Desktop/NativeReactSample/logo.png”)} /> ) export default ImagesExample Output Screen Density React Native offers a way to optimize images for different devices using @2x, @3x suffix. The app will load only the image necessary for particular screen density. The following will be the names of the image inside the img folder. [email protected] [email protected] Network Images When using network images, instead of require, we need the source property. It is recommended to define the width and the height for network images. App.js import React from ”react”; import ImagesExample from ”./image_example.js” const App = () => { return ( <ImagesExample /> ) } export default App image_example.js import React, { Component } from ”react” import { View, Image } from ”react-native” const ImagesExample = () => ( <Image source = {{uri:”https://pbs.twimg.com/profile_images/486929358120964097/gNLINY67_400x400.png”}} style = {{ width: 200, height: 200 }} /> ) export default ImagesExample Output Print Page Previous Next Advertisements ”;