Wednesday, March 25, 2020

How to start with React-native application development?



About react native




1)What is React Native ?

->The java script library for building user interface is called React.
->Typically used for web development.
->It is a collection of special react components.
->Componenet compiled to Native widgets.
->Native platform APIs exposed to javascript.
->Connect javascript and native platform code.



2)react-native eg:

const App = props =>{
  return(
       <View>
      <Text>Hay bot</Text>
   </View>
  )





3)Create a new react native app


  a)expo cli/tool(using this approach for this tutorial)

  ->third party service
  ->free
  ->managed app development workflow
  ->lots of convenience and utility features: simplifies development





  b)react native cli

  ->managed by reactnative team
  ->bare bone development
  ->almost no convenience or utility feature
  ->full flaxibility: integrate with any native code






4.1)how expo works?

->goto expo.io
->install Node.js in your PC if not
->get the command line tool(eg:Anaconda powershell prompt)
   npm install expo-cli --global
->Create your first project(navigate to the project directory folder)
    expo init my-new-project
    cd my-new-project
    expo start
->use expo-client app in android mobile and scan qr code yields to app lunch which your going to building.

->this should give up and running output app.
->open the app folder in any text editor to further code.





4.2)how react native cli work?

  (in one cmd)
->npm install -g react-native-cli
->npm install -g yarn
->react-native init myapp
->cd myapp
->react-native start
  (in another cmd and goto myapp folder)
->react-native run-android














a)reactnatibe basics

->core components
  i)built into react native
  ->"translation" to Native UI widgets provided by React Native

  ->eg:
    <View>
<Text>
<Button>/<Touchable...>
<TextInput>
<Image>




   ii)Your UIs/Custom Components

   ->Composed of these "Core" Components and other build-in Components

   ->eg:
     const MyTitle = props=>{
   return(
     <View>
   <Text>{props.title}</Text>
</View>
    );
}


iii)styling

->inline style
->styleSheet objects(prefered)
->written in javascript
->Based on CSS syntax, influenced by CSS




<===============lets build an simple app ======================>

1)initially app.js code :





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


export default function App() {
  return (
    <View style={styles.container}>
      <Text>hi dude</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});



2)After making app, app.js code:


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


export default function App() {
  const [enteredGoal, setEnteredGoal] = useState(' ');
  const [courseGoals, setCourseGoals] = useState([]);



  const goalInputHandler = (enteredText) => {
     setEnteredGoal(enteredText);
  };

  const addGoalHandler= ()=>{
     setCourseGoals(currentGoals =>[...currentGoals, enteredGoal]);
     console.log(enteredGoal);

  };





  return (
    <View style={styles.mainView}>
        <View style={styles.inputContainer}>
           <TextInput 
           placeholder={"Goal to achive"} 
           placeholderTextColor ={"green"}
           style={styles.inputField} 
           onChangeText = {goalInputHandler}
           />
           <Button 
           title={"Add me!"}  
           color={"coral"}
           onPress={addGoalHandler}
           />
        </View> 
        <View style={styles.showdataview}>
          {courseGoals.map((goal) => <Text>{goal}</Text>)}
        </View>
    </View>
  
  );
}




const styles = StyleSheet.create({
  mainView:{
    paddingTop:30,
    padding:5,
    
  },

  inputContainer:{
    flexDirection:"row",
    justifyContent:"space-evenly",
    },

  inputField:{
    backgroundColor:"lime",
    paddingStart:20,
    width:"75%",
    borderColor:"cornflowerblue",
    borderWidth: 2,
    },

  showdataview:{
    backgroundColor:"pink",
    height: "100%",
    borderColor: "black",
    borderWidth:2,
  },

});

Brief documentation of React ?




About react





1)Introduction



->It is a javaScript library for building user interfaces.
->It is used to build single page application.
->Allows us to create reusable UI components.
->It is created by facebook.
->It is tool for building UI components.





2)How does react works?

->It creates a VIRTUAL DOM in memory.
->It does necessary manipulation in memory before making change in browser DOM.
->It only changes what needs to be changed.




3)React Components

->components are independent and reusable bitd of code.
->components come in two type.




  a)Class component

  ->components name start with capital letter.
  ->Include the "extends React.Component" statement.
  ->Above statement create an inheritance to React.Component.
  ->Give your component excess to React.
  ->Requires a render() method, this method returns HTML.

  ->eg:
    class Car extends React.Component {
  render(){
    return <h1>I am class components </h1>;
  }
}
    //display the Car component in the "root" element
ReactDom.render(<Car/>, document.getElementById('root'));




  b)function component

  ->similer to class component.
  ->Does not have render() method.
  ->Does not support inheritance.
  ->class component is more preferred.

  ->eg:
    function Car(){
  return <h1>I am function components </h1>;
}
    //display the Car component in the "root" element
ReactDom.render(<Car/>, document.getElementById('root'));




4)Component constructor

->To initiate the component properties called state.
->used in class component.
->To support the inheritance of the parent component "super()" method
  is called in constructor function.
->"super()" method executes the parent components constructor function.
->class components have access to all the function of parent component
  "React.Component".

->eg:
  class Car extends React.Component{
   constructor(){
     super();
this.state = {name: "Ford"};
   }
   render(){
     return <h2>I am class component with constructor:{this.state.name}</h2>
   }
  }  





5)Props

->Way of handling component properties.

->eg:
  class Car extends React.Component{
    render(){
  return <h2>I am a {this.props.name} car </h2>;
}
  }
  ReactDom.render(<Car name={"Ford"}>,document.getElementById('root'));









6)Components in Components

->Can refer to components inside other components.

->eg:
  class Car extends React.Component{
    render(){
  return (
    <h2>I am a Car ! </h2>
  );
}
  }
  
  class Garage extends React.Component{
    render(){
  return(
    <div>
  <h1>Who lives in my Garage? </h1>
  <Car/>
</div>
  );
}
  }
  
  ReactDOM.render(<Garage />, document.getElementById('root'));
  




7)Components in files

->create a new file with a .js file extension and put the code inside it.

->eg:
  //code of a.js file
  import React from 'react';
  import ReactDOM from 'react-dom';

  class Car extends React.Component {
    render() {
      return <h2>Hi, I am a Car!</h2>;
    }
  }

  export default Car;
  
  //code of app.js file
  import React from 'react';
  import ReactDOM from 'react-dom';
  import Car from './App.js';

  ReactDOM.render(<Car />, document.getElementById('root'));








8)React Lifecycle


->Each component in react has a lifecycle.
->The three phases are:

  a)Mounting

  ->process of putting element into the DOM.
  ->react has four build-in methods that gets called,
    in order, when mounting a component.





    i)constructor()

->called by react every time when you make a component

->eg:
  class Header extends React.Component{
    constructor(props){
  super(props);
  this.state = {favoritecolor : "pink"};
}
render(){
  return(
    <h1>My favorite color is {this.state.favoritecolor}</h1>
  );
}
  } 
  ReactDOM.render(<Header/>, document.getElementById('root'));
  





    ii)getDerivedStateFromProps()

->method is called right before rendering the element(s) in the DOM.

->eg:
  class Header extends React.Component {
        constructor(props) {
          super(props);
          this.state = {favoritecolor: "red"};
        }

        static getDerivedStateFromProps(props, state) {
          return {favoritecolor: props.favcol };
        }

        render() {
          return (
            <h1>My Favorite Color is {this.state.favoritecolor}</h1>
          );
        }
      }

      ReactDOM.render(<Header favcol="yellow"/>, document.getElementById('root'));


    iii)render()

->Output the HTML documents in the DOM.

->eg:
  class Header extends React.Component{
    render(){
  return(
    <h1>This is the content of the header component</h1>
  );
}
  }
  
  ReactDom.render(<Header />, document.getElementById('root'));





    iv)componentDidMount()

    ->called after render() method

->eg:
  class Header extends React.Component {
        constructor(props) {
          super(props);
          this.state = {favoritecolor: "red"};
        }
        componentDidMount() {
          setTimeout(() => {
          this.setState({favoritecolor: "yellow"})
          }, 1000)
        }
        render() {
          return (
            <h1>My Favorite Color is {this.state.favoritecolor}</h1>
          );
        }
      }

      ReactDOM.render(<Header />, document.getElementById('root'));



 


  b)Updating

  ->second phase in which component updated.
  ->five methods are called.



    i)getDerivedStateFromProps()

->eg:
  class Header extends React.Component {
        constructor(props) {
          super(props);
          this.state = {favoritecolor: "red"};
        }

        static getDerivedStateFromProps(props, state) {
          return {favoritecolor: props.favcol };
        }

        changeColor = () => {
          this.setState({favoritecolor: "blue"});
        }

        render() {
          return (
            <div>
              <h1>My Favorite Color is {this.state.favoritecolor}</h1>
              <button type="button" onClick={this.changeColor}>Change color</button>
            </div>
          );
        }
     
}

     ReactDOM.render(<Header favcol="yellow"/>, document.getElementById('root'));





ii)shouldComponentUpdate()

->return boolean value, default value is true.

->eg:
  class Header extends React.Component {
        constructor(props) {
          super(props);
          this.state = {favoritecolor: "red"};
        }

        shouldComponentUpdate() {
          return false;
        }

        changeColor = () => {
          this.setState({favoritecolor: "blue"});
        }

        render() {
          return (
            <div>
              <h1>My Favorite Color is {this.state.favoritecolor}</h1>
              <button type="button" onClick={this.changeColor}>Change color</button>
            </div>
          );
        }
       }

      ReactDOM.render(<Header />, document.getElementById('root'));
  
 


 

iii)render()

->It is always called when components gets updated.

->eg:
  class Header extends React.Component {
        constructor(props) {
          super(props);
          this.state = {favoritecolor: "red"};
        }

        changeColor = () => {
          this.setState({favoritecolor: "blue"});
        }

        render() {
          return (
            <div>
              <h1>My Favorite Color is {this.state.favoritecolor}</h1>
              <button type="button" onClick={this.changeColor}>Change color</button>
            </div>
          );
        }
      }

      ReactDOM.render(<Header />, document.getElementById('root'));









iv)getSnapshotBeforeUpdate()

->have access to the props and state before the update.
->to use this method, you should also include the componentDidUpdate()

->eg:
  class Header extends React.Component {
        constructor(props) {
          super(props);
          this.state = {favoritecolor: "red"};
        }

        componentDidMount() {
          setTimeout(() => {
            this.setState({favoritecolor: "yellow"})
          }, 1000)
        }

        getSnapshotBeforeUpdate(prevProps, prevState) {
          document.getElementById("div1").innerHTML =
          "Before the update, the favorite was " + prevState.favoritecolor;
        }

        componentDidUpdate() {
          document.getElementById("div2").innerHTML =
          "The updated favorite is " + this.state.favoritecolor;
        }

        render() {
          return (
            <div>
              <h1>My Favorite Color is {this.state.favoritecolor}</h1>
              <div id="div1"></div>
              <div id="div2"></div>
            </div>
           );
        }
      }


     ReactDOM.render(<Header />, document.getElementById('root'));






v)componentDidUpdate()

->called after the component is updated in the DOM.

->eg:
  class Header extends React.Component {
        constructor(props) {
          super(props);
          this.state = {favoritecolor: "red"};
        }

        componentDidMount() {
          setTimeout(() => {
            this.setState({favoritecolor: "yellow"})
          }, 1000)
        }


        componentDidUpdate() {
          document.getElementById("mydiv").innerHTML =
          "The updated favorite is " + this.state.favoritecolor;
        }

        render() {
          return (
            <div>
              <h1>My Favorite Color is {this.state.favoritecolor}</h1>
              <div id="mydiv"></div>
            </div>
          );
        }
     }

     ReactDOM.render(<Header />, document.getElementById('root'));
  
 
 

 

  c)Unmounting

  ->phase when the component is removed from DOM.
  ->one method only.


    i)componentWillUnmount()

    ->called when component is about to remove

->eg:
  class Container extends React.Component {
        constructor(props) {
          super(props);
          this.state = {show: true};
        }

        delHeader = () => {
          this.setState({show: false});
        }

        render() {
          let myheader;
          if (this.state.show) {
            myheader = <Child />;
           };
          return (
            <div>
              {myheader}
              <button type="button" onClick={this.delHeader}>Delete Header</button>
            </div>
          );
        }
     }

    class Child extends React.Component {
      componentWillUnmount() {
        alert("The component named Header is about to be unmounted.");
      }
      
  render() {
        return (
          <h1>Hello World!</h1>
        );
      }
    }

    ReactDOM.render(<Container />, document.getElementById('root'));
 
 











Tuesday, March 24, 2020

About ES6 and it's new feature documentation ?


Introduction of ES6



->ECMA script is a scripting language standard and specification

 1)JavaScript
 2)Jscript
 3)ActionScript






->What is ES6?

  ->The most recent version of ECMAScript/ JavaScript
  ->very significant update with many changes
  ->first major update since ES5(2009)
  ->ES6 and ES2015 are the same thing




->Goals of ES6

  ->Be taken more seriously
  ->Fix some issues from ES5
  ->Backward compatibility -ES5 should work in ES6
  ->Modern syntax
  ->Better sccaling and better for big applications
  ->new feature in standard library






->What's New? An Overview

  ->let and const Declaration
  ->classes and inheritance
  ->Arrow function
  ->javascript classes
  ->Default parameter values
  ->Array.find()
  ->Array.findIndex()
  ->Exponentiation(**) (Ecma script 2016)







let's make dive into ES6



1)let

->allow to declare a variable with block scope
->eg:
  var x = 10;
  //here x is 10
  {
    let x = 2;
//here x is 2
  }
  // here x is 10





2)const

->allow  to declare a constant.
->similar to let variable, except that the value cannot be changed
->eg:
  var x = 10;
  //here x is 10
  {
    const x = 2;
//here x is 2
  }
  //here x is 10






3)Arrow functions

->short syntax for writing function expressions.
->using const is safer than using var,
  because a function expression is always constant value
->eg:
  //ES5
  var x = function(x, y){
  return x*y;
  }
  //ES6
  const x = (x, y) => x*y;
  
->eg:
  const x = (x,y) =>{return x*y };






4)Classes

->a class is a type of function, but instead of using the keyword function to
  initiate it,we use the keyword class, and the properties are assigned inside
  a constructor() method.
->use the keyword class to create a class, and always add a constructor method.
->the constructor method is called each time the class object is initialized.
->eg:
  class Car{
    constructor(brand){
  this.carname = brand;
}
  }
  mycar = new Car("Ford");





5)Default parameter values

->ES6 allows function parameter to have default value
->eg:
  function myFunnction(x, y = 10){
    // y is 10 if not passed and undefined
return x + y;
  }
  myFunction(5);  //will return 15
  myFunction(5,5);  // will return 10








6)Array.find()

->returns the value of the first array element that passes a test function
->the test function takes 3 arguments:
  1)the item value
  2)the item index
  3)the array itself
->eg:
  var numbers = [4,9,16,25,29];
  var first = numbers.find(myFunction);
  function myFunction(value, index, array){
    return value > 18;
  }








5)Array.findIndex()

->It retuens the index of the first array element that passes a test function
->It takes three arguments
  1)the item value
  2)the item index
  3)the array itself
->eg:
  var numbers = [4,9,16,25,29];
  var first = numbers.findIndex(myFunction);
  function myFunction(value, index, array){
    return value > 18;
  }






6)New number properties

->ES6 added the following properties to the number object
->EPSILON
->MIN_SAFE_INTEGER
->MAX_SAFE_INTEGER
->eg:
  var x = Number.EPSILON
  var x = Number.MIN_SAFE_INTEGER
  var x = Number.MAX_SAFE_INTEGER







7)New number methods

->ES6 added 2 new methods to the number object
->Number.isInteger()
  ->method returns true if the argumment is an integer
  ->eg:
    Number.isInteger(10);  // return true
    Number.isInteger(10.3);  // return false

->Number.isSafeInteger()
  ->method return true if the argument is a safe integer
  ->eg:
    Number.isSafeInter(10);  // returns true
    Number.isSafeInteger(1222234435454565554432332);  // return false






8)New global methods

->ES6 added 2 new global number methods
->isFinite()
  ->method return false if the argument is Infinity or NaN
  ->otherwise return true
  ->eg:
     isFinite(10/0);  // return false
     isFinite(10/1);  // return true

->isNaN()
  ->method return true if the argument is NaN.Otherwise it returns false
  ->eg:
    isNaN("hello");  // return true







9)Exponentiation Operator

->operator (**) raises the first operand to the power of the second operand.
->eg:
  var x = 5;
  var z = x ** 2;    // z = 25