React native tutorial:-

2


React native is used to create a native mobile application that can execute on Android and iOS platforms both, we can not create a web application using this.

React native is not used to create hybrid applications, it is used to create native common platform applications that provide separate configurations for iOS and Android devices.

How to install React Native 

1) Install java and set Java_Home Path under environment Variable

2)  Install Android studion and Set Android_Home path 

3)  Create AVD using android studio

4)  Run Avd Externally using following command

open command prompt and write following code

Default Android Location for Windows

C:/Users/MachineName/AppData/local/Android/SDK/emulator

Write follwing command to open emalutor

.\emulator.exe -avd "Testavd"

5)  Install React native globally in Operating System

 npx install -g react-native-cli

 react-native init AwesomeProject

 react-native run-android

6)  Now create Hello.js component

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

const Hello = () => {
  return (
    <View
      style={{
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
      }}>
      <Text>Hello, world!</Text>
    </View>
  );
};
export default Hello;

Call Hello.js to index.js

/**
 * @format
 */

import {AppRegistry} from 'react-native';
import App from './App';
import Hello from './Hello';
import {name as appName} from './app.json';

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



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

const Hello = () => {
  return (
    <View
      style={{
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
      }}>
     <Text style={styles.welcome}>Hello World</Text>
    </View>
  );
};
const styles = StyleSheet.create({  
    welcome: {  
      fontSize: 20,  
      textAlign: 'center',  
      margin: 10,  
    }  
  });  
export default Hello;

What is View Method:-
The View is the fundamental component of React Native for building a user interface.
It is a container that supports layout with flexbox, style, touch handling,
and accessibility controls.

It maps directly to the native view similar to whatever platform on React Native app
is running on.
It displays the components regardless with UIView, <div>, android.view, etc.

  1. import React, { Component } from 'react';  
  2. import { StyleSheet, View } from 'react-native';  
  3.   
  4. export default class HeightWidth extends Component {  
  5.     render() {  
  6.         return (  
  7.             <View>  
  8.                 <View style={styles.A} />  
  9.                 <View style={styles.B} />  
  10.                 <View style={styles.C} />  
  11.             </View>  
  12.         );  
  13.     }  
  14. }  
  15. const styles = StyleSheet.create({  
  16.     A:{  
  17.         width: 100, height: 100, backgroundColor: 'powderblue'  
  18.     },  
  19.     B:{  
  20.         width: 200, height: 200, backgroundColor: 'skyblue'  
  21.     },  
  22.     C:{  
  23.         height: 300, backgroundColor: 'steelblue'  
  24.     },  
  25. })  
Flex dimensions:-

Flex Dimensions

The flex property styles the component to expand and shrink it dynamically according to available space. Setting flex: 1 will fill all the available space to the component, and shared evenly among the other components of same as the parent. Higher the flex value, occupy component higher ratio of space compared to its siblings.

  1.  import React, { Component } from 'react';  
  2. import { StyleSheet, View } from 'react-native';  
  3.   
  4. export default class HeightWidth extends Component {  
  5.     render() {  
  6.         return (  
  7.             <View style={styles.container}>  
  8.                 <View style={styles.A} />  
  9.                 <View style={styles.B} />  
  10.                 <View style={styles.C} />  
  11.             </View>  
  12.         );  
  13.     }  
  14. }  
  15. const styles = StyleSheet.create({  
  16.     container:{  
  17.       flex:1  
  18.     },  
  19.     A:{  
  20.         flex:1,  
  21.         backgroundColor: 'powderblue',  
  22.     },  
  23.     B:{  
  24.         flex:2,  
  25.         backgroundColor: 'skyblue',  
  26.     },  
  27.     C:{  
  28.         flex:3,  
  29.         backgroundColor: 'steelblue',  
  30.     },  
  31. })  
React Native States:-

There are two types of data states and props in React Native that control the component
.
The component that uses the state is mutable. They can be changed later on if required. The props component is immutable, and it is fixed throughout the lifetime.

React Native state Example 1 In this example, we create a Text component with state data.
The content of Text component will be updated by clicking on it.
The event onPress call the setState, and it updates the state "myState" text. import React, {Component} from 'react'; import { Text, View } from 'react-native'; export default class App extends Component { state = { myState: 'THello SCS.' } updateState = () => this.setState({myState: 'HELLO WOrld'}) render() { return ( <View> <Text onPress={this.updateState}> {this.state.myState} </Text> </View> ); } }

React Native Props
The properties of React Native components are simply pronounced as props.
In React Native, most of the components can be customized at the time of their
creation with different parameters. These parameters are known as props. They are immutable, and they cannot be changed. One of the examples of props is a source property if Image component which controls
the image is displayed over the device screen.

import React, { Component } from 'react';  
import {  
  Platform,  
  StyleSheet,  
  Image,  
  Text,  
  View  
} from 'react-native';  
  
  
export default class App extends Component<{}> {  
  render() {  
    let imagePath = { uri: 'https://facebook.github.io/react-native/img/header_logo.png'};  
    return (  
        <View style={styles.container}>  
          <Text style={styles.welcome}>Welcome to React Native!</Text>  
          <Image source={imagePath} style={{width: 250, height: 250}} />  
        </View>  
    );  
  }  
}  
  
const styles = StyleSheet.create({  
  container: {  
    flex: 1,  
    justifyContent: 'center',  
    alignItems: 'center',  
    backgroundColor: '#a7a6a9',  
  },  
  welcome: {  
    fontSize: 30,  
    textAlign: 'center',  
    margin: 20,  
  }  
});  

Another Example:-

Using props in our own Component
We can also use props in our components. A single component can be used in many different places in the app by making slightly different properties in each place. To implement the props in our component, this.props is applied followed by the property.

For example, one of the basic React Native components is Text. When we create a Text component, we can use a prop "name" as props to control its appearance. We also apply the StyleSheet to the component which is used as our component.

App.js

 import React, { Component } from 'react';  
import { StyleSheet, Text, View } from 'react-native';  
  
class ChildClass extends Component {  
  render() {  
    return (  
        <View style={{alignItems: 'center'}}>  
          <Text style={styles.welcome}>Hello {this.props.name}!</Text>  
        </View>  
    );  
  }  
}  
  
export default class ParentsClass extends Component {  
  render() {  
    return (  
        <View style={{alignItems: 'center'}}>  
          <ChildClass name='Ashu' />  
          <ChildClass name='Aman' />  
          <ChildClass name='Max' />  
        </View>  
    );  
  }  
}  
const styles = StyleSheet.create({  
   welcome: {  
    fontSize: 30,  
  }  
});  
  
// skip this line if using Create React Native App  
//AppRegistry.registerComponent('MyReactNativeApp', () => ParentsClass);  

Create Addition Program in React Native:-

Addition Program using Class Component:-

import { Component } from "react";
import { View,Text, Button, TextInput} from "react-native";
export default class Stateexample extends Component
{
    state = {key:"",num1:0,num2:0}  //state declaration
 
    changeState=()=>
    {
        this.setState({key:(parseInt(this.state.num1) + parseInt(this.state.num2))})
    }
    render()
    {
        return(
        <View>
 <TextInput type="number" placeholder="Enter First Number"
onChangeText={v=>{this.setState({num1:v})}} />
            <TextInput type="number" placeholder="Enter Second Number"
onChangeText={v=>{this.setState({num2:v})}} />
           <Button title="click" onPress={this.changeState} />
           <Text>{this.state.key}</Text>
        </View>)
    }
}

Addition Program using Functional Component:-

import React, { useState } from 'react';
import { StyleSheet, View, Button, Alert, TextInput} from 'react-native';

export default function Add() {
    const [number1, setNumber1] = useState(0);
    const [number2, setNumber2] = useState(0);
    const [total, setTotal] = useState(number1 + number2);

    function addTogether() {
        const newTotal = number1 + number2;
        setTotal(newTotal);
        Alert.alert('Alert', 'Result is: ' + newTotal); // total has the old value in the render
    }
    return (
        <View style={styles.container}>
            <TextInput
                type="number"
                placeholder="0"
                value={number1}
                style={{height: 40,width:150,backgroundColor: 'azure', fontSize: 20}}  
                onChangeText={v => {
                    setNumber1(Number.parseInt(v)); // Use parsed value from onChangeText
                }}
            />
            <TextInput
                type="number"
                placeholder="0"
                value={number2}
                style={{height: 40,width:150,backgroundColor: 'azure', fontSize: 20}}  
                onChangeText={e => {
                    setNumber2(Number.parseInt(e)); // or get correct value from nativeEvent onChange
                }}
            />

            <Button onPress={addTogether} title="Tulos" />
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: 'red',
        alignItems: 'center',
        justifyContent: 'space-evenly',
    },
    input: {
        width: 200,
        borderColor: 'green',
        borderWidth: 1,
    },
});

Check Prime Program in React native:-

import { useState } from "react";
import { View,Text, Button, TextInput} from "react-native";
export default function  Prime()
{
    const[key,setKey] =useState("")
    const[num1,setNum1] = useState(0)
   
    const changeState=()=>
    {
       var out = ""
       const data = num1;
       var i=0;
       for(i=2;i<data;i++)
       {
        if(data%i==0)
        {
            out = "not prime";
            break
        }
       }
       if(data==i)
       {
        out = "prime"
       }
       setKey(out)
    }
   
        return(
        <View>
            <TextInput type="number" placeholder="Enter First Number"
onChangeText={v=>{setNum1(v)}} />
         
          <Button title="click" onPress={changeState} />
           <Text>{key}</Text>
        </View>)
    }


Assignment:-

Create Marksheet Program in React-native:-

Q) WAP to create a mark sheet of Students using five different subjects with the following condition?

1)  All Subject Marks Should be 0 to 100.

2) If only Subject Mark is <33 Then Student will Suppl

3) If the Minimum Two Subjects Marks is <33 Then Student Will Fail

4) IF all Subject Marks is > 33 then percentage and division should be calculated.

5)  IF only one subject Mark is >28 and <33 then 5 grace marks will be applied and the student will be passing by grace.

6)  Display Grace Subject Name, Distinction Subject name, Supp Subject name, and Failed Subject name. 


ListView Element in React-Native:-

React Native ListView React Native ListView is a view component which contains the list of items and displays in a vertical scrollable list.
The minimum API to create list view is ListView.DataSource.

It populates a simple array of data blobs, and instantiate a ListView component with
data source and a renderRow callback.
The renderRow takes a blob from data array and returns a renderable component.
Now ListView is deprecated because ListView Work can be managed by FlatList

import { Component } from "react"
import {View,StyleSheet,FlatList,Text,Alert} from "react-native"
const styles = StyleSheet.create({
    container: {
      flex: 1,
      paddingTop: 22,
    },
    item: {
      padding: 10,
      fontSize: 18,
      height: 44,
    },
  });
 
class ListViewExample extends Component {
    constructor()
    {
        super()
        this.state={dataSource:[
            {key: 'Devin'},
            {key: 'Dan'},
            {key: 'Dominic'},
            {key: 'Jackson'},
            {key: 'James'},
            {key: 'Joel'},
            {key: 'John'},
            {key: 'Jillian'},
            {key: 'Jimmy'},
            {key: 'Julie'},
          ]}
    }
    render(){

    return (
      <View style={styles.container}>
        <FlatList
          data={this.state.dataSource}
          renderItem={({item}) => <Text style={styles.item}>{item.key}</Text>}
        />
      </View>
    );
        }
  };
 
  export default ListViewExample;
React Native SectionList
The React Native SectionList component is a list view component
which sets the list of data into the broken logical section.
The broken data can be implemented using its section header prop renderSectionHeader. To implement the SectionList component,
we need to import SectionList from 'react-native' library. React Native SectionList Example In this example, we create a SectionList with title and data.
The section prop is used to create the list of title and data values.
The renderSectionHeader displays the header section of the list view. import React, { Component } from 'react'; import { AppRegistry, SectionList, StyleSheet, Text, View } from 'react-native'; export default class SectionListBasics extends Component { render() { return ( <View style={styles.container}> <SectionList sections={[ {title: 'A', data: ['ALTERED','ABBY','ACTION U.S.A.','AMUCK','ANGUISH']}, {title: 'B', data: ['BEST MEN','BEYOND JUSTICE','BLACK GUNN','BLOOD RANCH','BEASTIES']}, {title: 'C', data: ['CARTEL', 'CASTLE OF EVIL', 'CHANCE', 'COP GAME', 'CROSS FIRE',]}, ]} renderItem={({item}) => <Text style={styles.item}>{item}</Text>} renderSectionHeader={({section}) => <Text style={styles.sectionHeader}>{section.title}</Text>} keyExtractor={(item, index) => index} /> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: "#5ead97" }, sectionHeader: { paddingTop: 2, paddingLeft: 10, paddingRight: 10, paddingBottom: 2, fontSize: 22, fontWeight: 'bold', color: "#fff", backgroundColor: '#8fb1aa', }, item: { padding: 10, fontSize: 18, height: 44, } })
Adding Separator in SectionList
ItemSeparatorComponent prop adds the Separator between the lists of data.
Using this prop, call a renderSeparatormethod in which we add a View component as separator.

renderSeparator = () => {  
    return (  
        <View  
            style={{  
                height: 1,  
                width: "100%",  
                backgroundColor: "#000",  
            }}  
        />  
    );  
};  
   
ItemSeparatorComponent={this.renderSeparator}  

Performing action on SectionList items
To perform an action on clicking (pressing) the list item, we use a onPress prop. The onPress prop and handle the event in another method getListViewItem.

//handling onPress action  
    getListViewItem = (item) => {  
        alert(item);  
    }  
  
  renderItem={({item}) => <Text style={styles.item}  
  onPress={this.getListViewItem.bind(this, item)}>{item}</Text>}  



Post a Comment

2Comments

POST Answer of Questions and ASK to Doubt

  1. I am reading your post from the beginning, it was so interesting to read & I feel thanks to you for posting such a good blog,
    keep updates regularly.
    salesforcemasters.in/salesforce-lightning-training-in-hyderabad/

    ReplyDelete
Post a Comment