Category: 4. Components and APIs

https://cdn3d.iconscout.com/3d/premium/thumb/cloud-api-3d-icon-download-in-png-blend-fbx-gltf-file-formats–interface-components-computing-pack-network-communication-icons-8818345.png?f=webp

  • AsyncStorage

    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
    Ezoic

    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.

    React Native AsyncStorage
  • Geolocation

    In this chapter, we will show you how to use Geolocation.

    Step 1: App.js

    import React from 'react'
    import GeolocationExample from './geolocation_example.js'
    
    const App = () => {
       return (
    
      <GeolocationExample />
    ) } export default App
    Ezoic

    Step 2: Geolocation

    We will start by setting up the initial state for that will hold the initial and the last position.

    Now, we need to get current position of the device when a component is mounted using the navigator.geolocation.getCurrentPosition. We will stringify the response so we can update the state.

    navigator.geolocation.watchPosition is used for tracking the users’ position. We also clear the watchers in this step.

    AsyncStorageExample.js

    import React, { Component } from 'react'
    import { View, Text, Switch, StyleSheet} from 'react-native'
    
    class SwichExample extends Component {
       state = {
    
      initialPosition: 'unknown',
      lastPosition: 'unknown',
    } watchID: ?number = null; componentDidMount = () => {
      navigator.geolocation.getCurrentPosition(
         (position) => {
            const initialPosition = JSON.stringify(position);
            this.setState({ initialPosition });
         },
         (error) => alert(error.message),
         { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
      );
      this.watchID = navigator.geolocation.watchPosition((position) => {
         const lastPosition = JSON.stringify(position);
         this.setState({ lastPosition });
      });
    } componentWillUnmount = () => {
      navigator.geolocation.clearWatch(this.watchID);
    } render() {
      return (
         <View style = {styles.container}>
            <Text style = {styles.boldText}>
               Initial position:
            </Text>
            
            <Text>
               {this.state.initialPosition}
            </Text>
            
            <Text style = {styles.boldText}>
               Current position:
            </Text>
            
            <Text>
               {this.state.lastPosition}
            </Text>
         </View>
      )
    } } export default SwichExample const styles = StyleSheet.create ({ container: {
      flex: 1,
      alignItems: 'center',
      marginTop: 50
    }, boldText: {
      fontSize: 30,
      color: 'red',
    } })
  • Alert

    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
    Ezoic

    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

    React Native Alert

    When you click the button, you will see the following −

    React Native Alert Button
  • Text

    In this chapter, we will talk about Text component in React Native.

    This component can be nested and it can inherit properties from parent to child. This can be useful in many ways. We will show you example of capitalizing the first letter, styling words or parts of the text, etc.

    Step 1: Create File

    The file we are going to create is text_example.js

    Ezoic

    Step 2: App.js

    In this step, we will just create a simple container.

    App.js

    import React, { Component } from 'react'
    import TextExample from './text_example.js'
    
    const App = () => {
       return (
    
      <TextExample/>
    ) } export default App

    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: Text

    In this step, we will use the inheritance pattern. styles.text will be applied to all Text components.

    You can also notice how we set other styling properties to some parts of the text. It is important to know that all child elements have parent styles passed to them.

    text_example.js

    import React, { Component } from 'react';
    import { View, Text, Image, StyleSheet } from 'react-native'
    
    const TextExample = () => {
       return (
    
      <View style = {styles.container}>
         <Text style = {styles.text}>
            <Text style = {styles.capitalLetter}>
               L
            </Text>
            
            <Text>
               orem ipsum dolor sit amet, sed do eiusmod.
            </Text>
            
            <Text>
               Ut enim ad <Text style = {styles.wordBold}>minim </Text> veniam,
               quis aliquip ex ea commodo consequat.
            </Text>
            
            <Text style = {styles.italicText}>
               Duis aute irure dolor in reprehenderit in voluptate velit esse cillum.
            </Text>
            
            <Text style = {styles.textShadow}>
               Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia
               deserunt mollit anim id est laborum.
            </Text>
         </Text>
      
      </View>
    ) } export default TextExample const styles = StyleSheet.create ({ container: {
      alignItems: 'center',
      marginTop: 100,
      padding: 20
    }, text: {
      color: '#41cdf4',
    }, capitalLetter: {
      color: 'red',
      fontSize: 20
    }, wordBold: {
      fontWeight: 'bold',
      color: 'black'
    }, italicText: {
      color: '#37859b',
      fontStyle: 'italic'
    }, textShadow: {
      textShadowColor: 'red',
      textShadowOffset: { width: 2, height: 2 },
      textShadowRadius : 5
    } })

    You will receive the following output −

    React Native Text
  • Switch

    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.

    Ezoic

    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>
      );
    } }

    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: 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

    React Native Switch
  • Status Bar

    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.

    Ezoic

    Output

    React Native Status Bar
  • Picker

    In this chapter, we will create simple Picker with two available options.

    Step 1: Create File

    Here, the App.js folder will be used as a presentational component.

    App.js

    import React from 'react'
    import PickerExample from './PickerExample.js'
    
    const App = () => {
       return (
    
      <PickerExample />
    ) } export default App
    Ezoic

    Step 2: Logic

    this.state.user is used for picker control.

    The updateUser function will be triggered when a user is picked.

    PickerExample.js

    import React, { Component } from 'react';
    import { View, Text, Picker, StyleSheet } from 'react-native'
    
    class PickerExample extends Component {
       state = {user: ''}
       updateUser = (user) => {
    
      this.setState({ user: user })
    } render() {
      return (
         <View>
            <Picker selectedValue = {this.state.user} onValueChange = {this.updateUser}>
               <Picker.Item label = "Steve" value = "steve" />
               <Picker.Item label = "Ellen" value = "ellen" />
               <Picker.Item label = "Maria" value = "maria" />
            </Picker>
            <Text style = {styles.text}>{this.state.user}</Text>
         </View>
      )
    } } export default PickerExample const styles = StyleSheet.create({ text: {
      fontSize: 30,
      alignSelf: 'center',
      color: 'red'
    } })

    Output

    React Native Picker

    If you click on the name it prompts you all three options as −

    React Native Picker

    And you can pick one of them and the output will be like.

    React Native Picker
  • ActivityIndicator

    In this chapter we will show you how to use the activity indicator in React Native.

    Step 1: App

    App component will be used to import and show our ActivityIndicator.

    App.js

    import React from 'react'
    import ActivityIndicatorExample from './activity_indicator_example.js'
    
    const Home = () => {
       return (
    
      <ActivityIndicatorExample />
    ) } export default Home
    Ezoic

    Step 2: ActivityIndicatorExample

    Animating property is a Boolean which is used for showing the activity indicator. The latter closes six seconds after the component is mounted. This is done using the closeActivityIndicator() function.

    activity_indicator_example.js

    import React, { Component } from 'react';
    import { ActivityIndicator, View, Text, TouchableOpacity, StyleSheet } from 'react-native';
    
    class ActivityIndicatorExample extends Component {
       state = { animating: true }
       
       closeActivityIndicator = () => setTimeout(() => this.setState({
       animating: false }), 60000)
       
       componentDidMount = () => this.closeActivityIndicator()
       render() {
    
      const animating = this.state.animating
      return (
         <View style = {styles.container}>
            <ActivityIndicator
               animating = {animating}
               color = '#bc2b78'
               size = "large"
               style = {styles.activityIndicator}/>
         </View>
      )
    } } export default ActivityIndicatorExample const styles = StyleSheet.create ({ container: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center',
      marginTop: 70
    }, activityIndicator: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center',
      height: 80
    } })

    When we run the app, we will see the loader on screen. It will disappear after six seconds.

    React Native Activity Indicator
  • Modal

    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;
    Ezoic

    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 −

    React Native Open Modal

    If we click the button, the modal will open.

    React Native Modal
  • WebView

    In this chapter, we will learn how to use WebView. It is used when you want to render web page to your mobile app inline.

    Using WebView

    The HomeContainer will be a container component.

    App.js

    import React, { Component } from 'react'
    import WebViewExample from './web_view_example.js'
    
    const App = () => {
       return (
    
      <WebViewExample/>
    ) } export default App;

    Let us create a new file called WebViewExample.js inside the src/components/home folder.

    web_view_example.js

    import React, { Component } from 'react'
    import { View, WebView, StyleSheet }
    
    from 'react-native'
    const WebViewExample = () => {
       return (
    
      <View style = {styles.container}>
         <WebView
         source = {{ uri:
         'https://www.google.com/?gws_rd=cr,ssl&ei=SICcV9_EFqqk6ASA3ZaABA#q=tutorialspoint' }}
         />
      </View>
    ) } export default WebViewExample; const styles = StyleSheet.create({ container: {
      height: 350,
    } })

    The above program will generate the following output.

    React Native WebView