Category: 3. Core Concepts

https://cdn3d.iconscout.com/3d/premium/thumb/science-3d-illustration-download-in-png-blend-fbx-gltf-file-formats–atom-electron-class-education-vol02-college-theme-pack-school-illustrations-4133431.png?f=webp

  • Running Android

    We can run the React Native app on Android platform by running the following code in the terminal.

    react-native run-android
    

    Before you can run your app on Android device, you need to enable USB Debugging inside the Developer Options.

    When USB Debugging is enabled, you can plug in your device and run the code snippet given above.

    The Native Android emulator is slow. We recommend downloading Genymotion for testing your app.

    The developer menu can be accessed by pressing command + M.

  • Running IOS

    If you want to test your app in the IOS simulator, all you need is to open the root folder of your app in terminal and run −

    react-native run-ios
    

    The above command will start the simulator and run the app.

    We can also specify the device we want to use.

    react-native run-ios --simulator "iPhone 5s
    

    After you open the app in simulator, you can press command + D on IOS to open the developers menu. You can check more about this in our debugging chapter.

    You can also reload the IOS simulator by pressing command + R.

  • Router

    In this chapter, we will understand navigation in React Native.

    Step 1: Install Router

    To begin with, we need to install the Router. We will use the React Native Router Flux in this chapter. You can run the following command in terminal, from the project folder.

    npm i react-native-router-flux --save
    
    Ezoic

    Step 2: Entire Application

    Since we want our router to handle the entire application, we will add it in index.ios.js. For Android, you can do the same in index.android.js.

    App.js

    import React, { Component } from 'react';
    import { AppRegistry, View } from 'react-native';
    import Routes from './Routes.js'
    
    class reactTutorialApp extends Component {
       render() {
    
      return (
         <Routes />
      )
    } } export default reactTutorialApp AppRegistry.registerComponent('reactTutorialApp', () => reactTutorialApp)

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    Step 3: Add Router

    Now we will create the Routes component inside the components folder. It will return Router with several scenes. Each scene will need key, component and title. Router uses the key property to switch between scenes, component will be rendered on screen and the title will be shown in the navigation bar. We can also set the initial property to the scene that is to be rendered initially.

    Routes.js

    import React from 'react'
    import { Router, Scene } from 'react-native-router-flux'
    import Home from './Home.js'
    import About from './About.js'
    
    const Routes = () => (
       <Router>
    
      &lt;Scene key = "root"&gt;
         &lt;Scene key = "home" component = {Home} title = "Home" initial = {true} /&gt;
         &lt;Scene key = "about" component = {About} title = "About" /&gt;
      &lt;/Scene&gt;
    </Router> ) export default Routes
    Ezoic

    Step 4: Create Components

    We already have the Home component from previous chapters; now, we need to add the About component. We will add the goToAbout and the goToHome functions to switch between scenes.

    Home.js

    import React from 'react'
    import { TouchableOpacity, Text } from 'react-native';
    import { Actions } from 'react-native-router-flux';
    
    const Home = () => {
       const goToAbout = () => {
    
      Actions.about()
    } return (
      &lt;TouchableOpacity style = {{ margin: 128 }} onPress = {goToAbout}&gt;
         &lt;Text&gt;This is HOME!&lt;/Text&gt;
      &lt;/TouchableOpacity&gt;
    ) } export default Home

    About.js

    import React from 'react'
    import { TouchableOpacity, Text } from 'react-native'
    import { Actions } from 'react-native-router-flux'
    
    const About = () => {
       const goToHome = () => {
    
      Actions.home()
    } return (
      &lt;TouchableOpacity style = {{ margin: 128 }} onPress = {goToHome}&gt;
         &lt;Text&gt;This is ABOUT&lt;/Text&gt;
      &lt;/TouchableOpacity&gt;
    ) } export default About

    The app will render the initial Home screen.

    React Native Router

    You can press the button to switch to the about screen. The Back arrow will appear; you can use it to get back to the previous screen.

    React Native Router
  •  Debugging

    React native offers a couple of methods that help in debugging your code.

    In App Developer Menu

    You can open the developer menu on the IOS simulator by pressing command + D.

    On Android emulator, you need to press command + M.

    React Native Debugging Developer Menu
    • Reload − Used for reloading simulator. You can use shortcut command + R
    • Debug JS Remotely − Used for activating debugging inside browser developer console.
    • Enable Live Reload − Used for enabling live reloading whenever your code is saved. The debugger will open at localhost:8081/debugger-ui.
    • Start Systrace − Used for starting Android marker based profiling tool.
    • Show Inspector − Used for opening inspector where you can find info about your components. You can use shortcut command + I
    • Show Perf Monitor − Perf monitor is used for keeping track of the performance of your app.
  • Animations

    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 (
         &lt;TouchableOpacity style = {styles.container} onPress = {this.animatedBox}&gt;
            &lt;Animated.View style = {&#91;styles.box, animatedStyle]}/&gt;
         &lt;/TouchableOpacity&gt;
      )
    } } export default Animations const styles = StyleSheet.create({ container: {
      justifyContent: 'center',
      alignItems: 'center'
    }, box: {
      backgroundColor: 'blue',
      width: 50,
      height: 100
    } })
  • Buttons

    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 (
    
      &lt;Button
         onPress = {handlePress}
         title = "Red button!"
         color = "red"
      /&gt;
    ) } export default App

    If the default Button component does not suit your needs, you can use one of the following components instead.

    Buttons Redbutton

    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 (
    
      &lt;View style = {styles.container}&gt;
         &lt;TouchableOpacity&gt;
            &lt;Text style = {styles.text}&gt;
               Button
            &lt;/Text&gt;
         &lt;/TouchableOpacity&gt;
      &lt;/View&gt;
    ) } export default App const styles = StyleSheet.create ({ container: {
      alignItems: 'center',
    }, text: {
      borderWidth: 1,
      padding: 25,
      borderColor: 'black',
      backgroundColor: 'red'
    } })
    Buttons Touchopacity
    Ezoic

    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 (
    
      &lt;View style = {styles.container}&gt;
         &lt;TouchableHighlight&gt;
            &lt;Text style = {styles.text}&gt;
               Button
            &lt;/Text&gt;
         &lt;/TouchableHighlight&gt;
      &lt;/View&gt;
    ) } export default App const styles = StyleSheet.create ({ container: {
      alignItems: 'center',
    }, text: {
      borderWidth: 1,
      padding: 25,
      borderColor: 'black',
      backgroundColor: 'red'
    } })

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    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 (
    
      &lt;View style = {styles.container}&gt;
         &lt;TouchableNativeFeedback&gt;
            &lt;Text style = {styles.text}&gt;
               Button
            &lt;/Text&gt;
         &lt;/TouchableNativeFeedback&gt;
      &lt;/View&gt;
    ) } export default Home const styles = StyleSheet.create ({ container: {
      alignItems: 'center',
    }, text: {
      borderWidth: 1,
      padding: 25,
      borderColor: 'black',
      backgroundColor: 'red'
    } })
    Ezoic

    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>
  • HTTP

    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 (
    
      &lt;HttpExample /&gt;
    ) } 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) =&gt; response.json())
      .then((responseJson) =&gt; {
         console.log(responseJson);
         this.setState({
            data: responseJson
         })
      })
      .catch((error) =&gt; {
         console.error(error);
      });
    } render() {
      return (
         &lt;View&gt;
            &lt;Text&gt;
               {this.state.data.body}
            &lt;/Text&gt;
         &lt;/View&gt;
      )
    } } export default HttpExample

    Output

    React Native HTTP
  • Images

    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 (
    
      &lt;ImagesExample /&gt;
    ) } 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

    React Native Images
    Ezoic

    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]
    

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    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 (
    
      &lt;ImagesExample /&gt;
    ) } 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

    Network Images
  • ScrollView

    In this chapter, we will show you how to work with the ScrollView element.

    We will again create ScrollViewExample.js and import it in Home.

    App.js

    import React from 'react';
    import ScrollViewExample from './scroll_view.js';
    
    const App = () => {
       return (
    
      &lt;ScrollViewExample /&gt;
    ) }export default App

    Scrollview will render a list of names. We will create it in state.

    Ezoic

    ScrollView.js

    import React, { Component } from 'react';
    import { Text, Image, View, StyleSheet, ScrollView } from 'react-native';
    
    class ScrollViewExample extends Component {
       state = {
    
      names: &#91;
         {'name': 'Ben', 'id': 1},
         {'name': 'Susan', 'id': 2},
         {'name': 'Robert', 'id': 3},
         {'name': 'Mary', 'id': 4},
         {'name': 'Daniel', 'id': 5},
         {'name': 'Laura', 'id': 6},
         {'name': 'John', 'id': 7},
         {'name': 'Debra', 'id': 8},
         {'name': 'Aron', 'id': 9},
         {'name': 'Ann', 'id': 10},
         {'name': 'Steve', 'id': 11},
         {'name': 'Olivia', 'id': 12}
      ]
    } render() {
      return (
         &lt;View&gt;
            &lt;ScrollView&gt;
               {
                  this.state.names.map((item, index) =&gt; (
                     &lt;View key = {item.id} style = {styles.item}&gt;
                        &lt;Text&gt;{item.name}&lt;/Text&gt;
                     &lt;/View&gt;
                  ))
               }
            &lt;/ScrollView&gt;
         &lt;/View&gt;
      )
    } } export default ScrollViewExample const styles = StyleSheet.create ({ item: {
      flexDirection: 'row',
      justifyContent: 'space-between',
      alignItems: 'center',
      padding: 30,
      margin: 2,
      borderColor: '#2a4944',
      borderWidth: 1,
      backgroundColor: '#d2f7f1'
    } })

    When we run the app, we will see the scrollable list of names.

    React Native ScrollView
  • Text Input

    In this chapter, we will show you how to work with TextInput elements in React Native.

    The Home component will import and render inputs.

    App.js

    import React from 'react';
    import Inputs from './inputs.js'
    
    const App = () => {
       return (
    
      &lt;Inputs /&gt;
    ) } export default App
    Ezoic

    Inputs

    We will define the initial state.

    After defining the initial state, we will create the handleEmail and the handlePassword functions. These functions are used for updating state.

    The login() function will just alert the current value of the state.

    We will also add some other properties to text inputs to disable auto capitalisation, remove the bottom border on Android devices and set a placeholder.

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    inputs.js

    import React, { Component } from 'react'
    import { View, Text, TouchableOpacity, TextInput, StyleSheet } from 'react-native'
    
    class Inputs extends Component {
       state = {
    
      email: '',
      password: ''
    } handleEmail = (text) => {
      this.setState({ email: text })
    } handlePassword = (text) => {
      this.setState({ password: text })
    } login = (email, pass) => {
      alert('email: ' + email + ' password: ' + pass)
    } render() {
      return (
         &lt;View style = {styles.container}&gt;
            &lt;TextInput style = {styles.input}
               underlineColorAndroid = "transparent"
               placeholder = "Email"
               placeholderTextColor = "#9a73ef"
               autoCapitalize = "none"
               onChangeText = {this.handleEmail}/&gt;
            
            &lt;TextInput style = {styles.input}
               underlineColorAndroid = "transparent"
               placeholder = "Password"
               placeholderTextColor = "#9a73ef"
               autoCapitalize = "none"
               onChangeText = {this.handlePassword}/&gt;
            
            &lt;TouchableOpacity
               style = {styles.submitButton}
               onPress = {
                  () =&gt; this.login(this.state.email, this.state.password)
               }&gt;
               &lt;Text style = {styles.submitButtonText}&gt; Submit &lt;/Text&gt;
            &lt;/TouchableOpacity&gt;
         &lt;/View&gt;
      )
    } } export default Inputs const styles = StyleSheet.create({ container: {
      paddingTop: 23
    }, input: {
      margin: 15,
      height: 40,
      borderColor: '#7a42f4',
      borderWidth: 1
    }, submitButton: {
      backgroundColor: '#7a42f4',
      padding: 10,
      margin: 15,
      height: 40,
    }, submitButtonText:{
      color: 'white'
    } })

    Whenever we type in one of the input fields, the state will be updated. When we click on the Submit button, text from inputs will be shown inside the dialog box.

    React Native Text Input

    Whenever we type in one of the input fields, the state will be updated. When we click on the Submit button, text from inputs will be shown inside the dialog box.

    React Native Text Input