How to Create React Native Application & Native Components

 

Introduction to React Native:

React native:



React Native Is a Javascript Framework for Developing Native mobile applications for android and ios.  It uses the React framework and offers large amount of inbuilt components and APIs. React Native applications are real mobile applications and not just web applets. Facebook released the first version of React Native in March 2015.
It uses only JavaScript to build a mobile application. It is like React, which uses native component rather than using web components as building blocks.

 


What are React Native apps?

React Native apps are not web application. They are running on a mobile device, and it does not load over the browser. React Native apps are the real native app, The user interface and everything are compiled to native code.

History of React Native

  • Facebook develops the React Native in 2013 for their internal project Hackathon.
  • It was released publically in January 2015 as React.js, and in March 2015, Facebook announced that React Native is open and available on GitHub.
  • React Native was initially developed for the iOS application. However, recently it also supports the Android operating system.

 

React js Vs React Native:

Reactjs: Reactjs is a javascript library used for creating user interfaces and UI components. It is open source and mainly used for frontend development. It is mainly used for web development.

React Native: it is a open source mobile application development framework, created by facebook.  Used for developing mobile applications for android and ios. It enables developers to work with react library and native platform capabilities.

Prerequisite:

To work with React Native one should Know,

1.React   2. javascript

How React Native works:

In React we use HTML elements are used to create components ,but in react native we use special native components.

In React Native HTML elements and CSS are not supported.

The react components are Compiled to native elements to run on Native platforms.

The styling of a component is written in Javascript using the CSS syntax.

 

Advantages of React Native:

  • Cross-Platform Usage: Provide facility of "Learn once write everywhere", it works for both platform Android as well iOS devices.
  • Class Performance: The code written in React Native are compiled into native code, which enables it for both operating systems as well as it functions in the same way on both the platforms.
  • JavaScript: The JavaScript knowledge is used to build native mobile apps.
  • Community: The large community of React and React Native around helps us to find any answer we require.
  • Hot Reloading: Making a few changes in the code of your app will be immediately visible during development. If business logic is changed, its reflection is live reloaded on screen.

 

Creating A React Native App For android.

To create a react Native app First step is setting up the development environment.

You can Create development environment in two ways.

1.React –Native –Cli

2.Expo-cli

React-Native-Cli  VS  Expo-cli

React-Native-cli:

  • Created by React Native community and it is a open source.
  • You have the control ,you will configure the React-Native-Cli on your own.
  • It is More Complicated , But provides More Control And More Feature to the Developer.

Expo-cli:

  • It is free and third party service.
  • Less Complicated compare to React-Native-Cli.
  • Less Control And Limited to Expo eco system.

 

In this We discuss only React-Native-Cli.

Using React Native Cli in Windows/Linux you Can only Create Android application.

Using React Native Cli in Macos supports both Andriod and Ios.

 

Creating a Environment Setup in Windows:

Dependencies:

Nodejs

Java Se Development Kit(Jdk)

Android Studio

 

1)Installing The Dependencies :

First install the Chocolaty package manager for windows.

Then by Running the Following command You can Install Nodejs and jdk.

                     choco install -y nodejs-lts openjdk11

 

2)Android development environment:

 Step 1: is installing Android Studio ,While Installing The Android studio make sure the following Boxes are checked.

1.Andriod Sdk, 2.Android Sdk Platform, 3..Android Virtual device

Step 2: Android Studio Automatically installs The latest version By Default , But the Android 12 Is required Can be installed using sdk Manager.

Select Sdk Mager àShow Packages àSelect Android 12 àMake sure The Following Item Also Checked.

1.Android SDK Platform latest version.

2. Intel x86 Atom_64 System Image or Google APIs Intel x86 Atom System Image.

Finally Click Apply to download and install.

 

3)Configure the ANDROID_HOME Environment variable:

Click on Edit Environment variable àCreate a new Environment Variable named ANDROID_HOME and value as Android Sdk location From Sdk Manager.

You Can Verify The ANDROID_HOME Added by Running The Following Command In PowerShell.

              Get-ChildItem -Path Env:\

 

4)Add platform Tools  to path:

Click On Edit Environment Variable àselect Path variable àClick edit àClick New and add the path.

  The default path is  =   %LOCALAPPDATA%\Android\Sdk\platform-tools.

 

Preparing The Android device:

You need a Android device to run the application it can be either a physical device or a virtual device,

Using physical Device:

To use a physical device you should follow the Instructions given in the Link:

https://reactnative.dev/docs/running-on-device.

Using A virtual device:

To use A Virtual device follow the instructions In the link:

https://developer.android.com/studio/run/managing-avds.html

 

Creating A React Native Application Using React Native-cli:

You Can Create your project using react Native  By running The following Command,

          npx react-native init projectname

On the execution of the above command will create a folder on the project name with all the files need to run an application , you can navigate to the project folder using any IDE  and run the application .

Running your React Native application:

Step 1: Start Metro

First, you will need to start Metro, the JavaScript bundler that ships with React Native. Metro "takes in an entry file and various options, and returns a single JavaScript file that includes all your code and its dependencies.

You Can Start Metro By Running the Following command,

            npx react-native start.

 Note: Before starting the metro you should start your virtual device using android studio

Step 2: Start your application

Let Metro Bundler run in its own terminal. Open a new terminal inside your React Native project folder. Run the following,

                       npx react-native run-android

If everything is set up correctly, you should see your new app running in your Android emulator shortly.

 


Creating A Hello World App:

You can create your own app by modifying the codes in the app .js file .then reload the app to seethe changes.

Lets us create a first hello world app in the react native.

I modified the App.js file Codes as below,

 

import React from 'react';

import { View, Text} from 'react-native';

 

const App = () => {

 return(

<View>

<Text>Hello world</Text>

 

</View>

 )

 

};

export default App;

 

then run the emulator using android studio, while running the app for the first time only we need to run metro an d the app separately ,after that you don’t need to  run the metro separately, you just need to run the app it will automatically run the metro on terminal.

In index.js the App component from App.js is imported and rendered inside the root component.

import {AppRegistry} from 'react-native';

import App from './App';

import {name as appName} from './app.json';

 

AppRegistry.registerComponent(appName, () => App);

 

Now let us run the application By using the command,

              Npx npx react-native run-android

 

It will run the app on the emulator.

 


As we know React Native don’t support HTML elements ,it only supports native components, Let we see how to create them.

                

React Native Core  Components:

What is React Native core Components?

In Expo and React Native, components are translated to native components for the platform it’s running on. To help you get started, React Native provides a set of ready-to-use components for your app. These components are called “core components” and most of them have built-in Android and iOS implementations.

You can import these components from the react-native package. These Components are very essential for a react native app. Some of most common core components are,

1.View:

One of the most fundamental core components is the View component. With View, you can create responsive layouts using flex box or add basic styling to nested components.

The component is best comparable with a div HTML element. Just like div, the View component is not visible unless styling is applied. We can apply this styling through the style property.

Example:

import React from "react";

import { View, Text } from "react-native";

 

const App = () => {

  return (

    <View

      style={{flex:1,

        }}

    >

      <View style={{ backgroundColor: "blue", flex: 0.3 }} />

      <View style={{ backgroundColor: "red", flex: 0.5 }} />

      <Text style={{backgroundColor:'yellow'}}>Hello World!</Text>

    </View>

  );

};

 

2. Style sheet:

Style sheets are used for moving the style separately from the render function,it looks similar to CSS.By moving styles away from the render function, you're making the code easier to understand.

 

import React from "react";

import { View, Text,StyleSheet } from "react-native";

 

const App = () => {

  return (

    <View

      style={styles.body}

    >

      <View style={styles.View1} />

      <View style={styles.View2} />

      <Text style={styles.text}>Hello World!</Text>

    </View>

  );

};

 

const styles= StyleSheet.create({

  body:{flex:1,padding:20,backgroundColor:'orange'},

  View1:{backgroundColor:'red',flex:0.4},

  View2:{backgroundColor:'blue',flex:0.4},

  text:{backgroundColor:'green'}

})

 

export default App

 

Output:

 


 

3. Scroll view:

The Scroll View is a  scrolling container that can contain multiple components and views.The scrollable items can be heterogeneous, and you can scroll both vertically and horizontally (by setting the horizontal property).

Example:

import React from "react";

import { View, Text,StyleSheet, ScrollView, } from "react-native";

 

const App = () => (

  <View style={{ flex: 1, justifyContent: 'center' }}>

    <Text style={{ fontSize: 24, textAlign: 'center' }}>

      Scroll me!

    </Text>

    <View style={{ height: 150, backgroundColor: 'white' }}>

      {/* This is our scrollable area */}

      <ScrollView horizontal>

        <View style={{ width: 200, height: 100, backgroundColor: 'red' }} />

        <View style={{ width: 200, height: 100, backgroundColor: 'green' }} />

        <View style={{ width: 200, height: 100, backgroundColor: 'blue' }} />

      </ScrollView>

    </View>

  </View>

);

 

export default App

 

Output:

 


4. Safeareaview:

It is similar to view Component, SafeAreaView component is to render content within the safe area boundaries of a device. All smartphones nowadays come with an edge-to-edge display. But smartphones must have some space left for the front cameras. Therefore all smartphones come with a notch or punch hole on the screen to fit the camera inside. It makes designing an app difficult for the developers because sometimes UI components go under this notch and it disrupts the design. 

If you use the normal View component in React Native, you have to take care of this situation by yourself and make sure all the UI components render within the safe are boundaries of a device. But SafeAreaView component takes away that headache from you and makes sure everything works fine on a device. Every component you write in SafeAreaView will render within the safe area boundaries of a device.

 

 

5. Text:

A React component for displaying text. Text supports nesting, styling, and touch handling.

Example:

import React from "react";

import {View, Text,StyleSheet} from 'react-native';

 

const Textcomp =() =>{

    return(

        <View style={styles.body}>

            <Text style={styles.text}>normal text Component</Text>

 

            <Text style={styles.outertext}>

                outer text

                <Text style={styles.innertext}>inner text</Text>

            </Text>

        </View>

    )

}

 

const styles=StyleSheet.create({

    body:{flex:1,backgroundColor:'grey'},

    text:{color:'blue',fontSize:30,margin:10},

    outertext:{color:'green',fontSize:30,margin:10},

    innertext:{color:'red',fontSize:30,margin:10},

})

 

Output:



6. Image:

Almost every app displays images. This content can be rendered in React Native using the Image component. It’s similar to the <img> HTML element, but the Image component has more features.

One of the additional features of <Image> is the ability to load images from different sources. This could be a publicly accessible https:// link, local file:// reference,  or image imported as module with require. Each of the image sources has its own benefits.

A React component for displaying different types of images, including network images, static resources, temporary local images, and images from local disk.

Static Image Resources

The static images are added in app by placing it in somewhere in the source code directory and provide its path as:

     <Image source={require('./image_name')} />  

 

Network Images:

network images are also be displayed in the Image component. To access the network image, it is required to specify the dimensions of image manually. and place the image component inside the View Component.

   <Image source={{uri: 'https://url_of_image.png'}}  

       style={{width: 60, height: 60}} />  

by placing the Image Component inside a view component you will get output like,

 

output:



7. Button component:

Besides all visual components, every app requires interactive components. One of the most frequent interactions is a “click” or “press” interaction. Most of the core components have support for press interactions. But, there is one component specifically created to handle simple presses: the Button component.

Example:

const App = () => {

  return (

    <View style={styles.body} >

       <Button title="pressme!" />

    </View>

  );

};

 

const styles= StyleSheet.create({

  body:{flex:1,backgroundColor:'white',justifyContent:'center'},

})

 

Output:

 


8. Text Input:

The TextInput component is created to capture textual and numeric input. This component is best comparable with the <input> HTML element.To listen to input changes from the user, we can use the onChangeText event handler. This event handler receives the input as a string, provided by the user.

Example:

function App() {

  const [name, setName] = useState('');

 

 

  return (

    <View style={{flex:1,alignItems:"center",justifyContent:'center'}}>

 

      <Text style={{color:'black',fontWeight:'bold'}}>Enter name:</Text>

      <TextInput

         

        style={{color:'blue',borderWidth: 1,borderColor: 'grey',padding: 8,margin: 10,width: 200,}}

        onChangeText={value => setName (value)} />

 

      <Text style={{color:'black'}}>name: {name}</Text>

    </View>

  );

}

 

export default App

 

output:

 


Props:

Most components can be customized when they are created, with different parameters. These creation parameters are called props.

Your own components can also use props. This lets you make a single component that is used in many different places in your app, with slightly different properties in each place. Refer to props.YOUR_PROP_NAME in your functional components or this.props.YOUR_PROP_NAME in your class components

Example:

import React from "react";

import {View, Text,Image,StyleSheet} from 'react-native';

 

const Welcome=(props)=>{

    return(

        <View style={{flex:0.2, margin:50}}>

            <Text style={{color:'black',fontSize:20,fontStyle:'italic'}}>

                hello {props.msg}

            </Text>

        </View>

    )

}

export default Welcome

 

while rendering you should pass the component with value inside the main component.

 <Welcome msg="welcome to React native"/>

 

You can use the same component with  different values in multiple locations.

 

Output:



State:

Unlike props that are read-only and should not be modified, the state allows React components to change their output over time in response to user actions, network responses and anything else.

Example:

import React,{useState} from "react";

import { View,Text, StyleSheet, Button,} from "react-native";

 

const Statecomp =(props)=>{

   

        const [msg, setMsg]=useState('Hello welcome to reactnative')

        const change_value=()=>{setMsg('lets start learning')}

        return(

            <View style={{flex:0.3}}>

                <Text style={{color:'black',fontSize:20, backgroundColor:"yellow"}}>  {msg}</Text>

                <Button title="enter" style={{backgroundColor:'blue', height:100, }} onPress={change_value}/>

            </View>

        )

   

}

Output:

(usestate)

(set state)
 



List views In React Native

There are two types of list available in react native to propagate your data on screen.

1. Flat List

2. Section List.

Flat List:

In react native flat list component is used to show fixed number of items which fits the screen or window of the device.

Remaining item of the list will render on scroll action. It will only scroll the List elements only not the screen.It is the simplest way to show data in list in react-native. One of the silent feature of flat list is that it provide header and footer support.

Example:

import React from "react";

import {View, Text, FlatList,} from "react-native";

const Data=[

    {id:1, name:'sugu'},

    {id:2, name:'sugu'},

    {id:3, name:'sugu'},

    {id:4, name:'sugu'},

    {id:5, name:'sugu'},

    {id:6, name:'sugu'},

    ]

const Flatlistcomp=()=>{

return(

    <View style={{flex:1}}>

        <Text style={{fontSize:20,backgroundColor:'black',color:'yellow',margin:10,alignItems:"center",justifyContent:'center'}}>FlatList</Text>

        <FlatList

       

        data={Data}

        renderItem={({item})=><Text style={{color:'black',fontSize:30,backgroundColor:'orange',margin:10,height:60}}>{item.name}</Text>}

        />

    </View>

)

}

 

Output:

 


List With map function:

When you render a list in react native using javascript map function,it will render the whole list items you can see the items using scrollview component

Example:

import React from "react";

import {View, Text,ScrollView,} from "react-native";

const Data=[

    {id:1, name:'sugu'},

    {id:2, name:'sugu'},

    {id:3, name:'sugu'},

    {id:4, name:'sugu'},

    {id:5, name:'sugu'},

    {id:6, name:'sugu'},

 

    ]

 

    const Listcomp=()=> {

        return (

          <View style={{flex:1}}>

            <Text style={{color:'black'}}>normal list</Text>

            {Data.map((person) => {

              return (

                <View key={person.id}>

                  <Text style={{color:'black',fontSize:30,backgroundColor:'orange',margin:10,height:100}}>{person.name}</Text>

                </View>

              );

            })}

          </View>

        );

      }

       

 Section List:

Section lists are similar to flat lists but they have Section headers to separate the groups of rows. Section list render each item in their input section. Each item in the section should be a object with unique id and array of data.

The render section header is a function which takes item from the sections array and maps it to a react element.

The render item is the function which takes the item from the array.

 

Example:

import React from "react";

import {View ,Text,Stylesheet,SectionList} from 'react-native';

 

const DATA=[

    {title:'A',data:['mysql','sqlite','redis']},

    {title:'b',data:['react','html','css','bootstrap']},

    {title:'c',data:['python','java','r']}

   

]

 

const Seclistcomp=()=>{

    return (<View style={{flex:1}}>

        <SectionList

          keyExtractor={(item, index) => index.toString()}

          sections={DATA}

          renderItem={({ item }) => (

            <Text style={{color:'black',fontSize:30,backgroundColor:'blue',marginLeft:10,height:60}}>{item}</Text>

          )}

          renderSectionHeader={({section})=>(

            <View style={{flex:1}}>

              <Textstyle={{color:'black',fontSize:30,backgroundColor:'grey',

marginTop:20,height:60}}>{section.title}</Text>

            </View>

          )}

        />

        </View>

        );

    };

 

Output:

 



 

 

 

 

 

 

 

 

 

 

 

 

 

Comments

Popular posts from this blog

Oracle Database Server Architecture: Overview

Oracle E-Business Suite (EBS) - Introduction

Advantages and Disadvantages of React Native