Thursday, 24 February 2022

Date Validation

 Requirements :

1) All dates before current date are disabled

2) If we select current date, validation message should come (Date should not equal to current date)

3) Date can be valid within the one year from current date.

.ts file code:

todayDate: Date=new Date();

validDate:boolean = false;

validDate2:boolean = false;

enteredDate: string;

nextYearDate: string;


renewDateChange(){

this.enteredDate = moment(event.value).format('YYYY-MM-DD');

    // checking Entered Date is equal to todays date

    if(this.enteredDate === moment(new Date()).format('YYYY-MM-DD')){

      this.validDate2 = true;

    }else {

      this.validDate2 = false;

      // Current date

      const aYearFromNow = new Date();

      // setting validation for 1 year

      aYearFromNow.setFullYear(aYearFromNow.getFullYear() + 1);

      this.nextYearDate = moment(aYearFromNow).format('YYYY-MM-DD')

      this.validDate = (this.enteredDate <= this.nextYearDate) ? false : true;

    }

}

.html file


<mat-form-field fxFlex="25" class="formField ">

          <mat-label>Program renew by*</mat-label>

          <input matInput [matDatepicker]="picker" [min]="todayDate" formControlName="renewalDate" (dateInput)="renewDateChange($event)" >

          <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>

          <mat-datepicker #picker></mat-datepicker>

          <mat-error *ngIf="f.renewalDate.errors">

            <span *ngIf="f.renewalDate.errors.required">Please provide Renewal Date </span>

          </mat-error>

        </mat-form-field>



PostedBy: pankaj_bhakre

Sunday, 20 February 2022

HOC Theory

 A higher-order component (HOC) is an advanced technique in React for reusing component logic. HOCs are not part of the React API. They are a pattern that emerges from React’s compositional nature.


Concretely, a higher-order component is a function that takes a component and returns a new component.



PostedBy: pankaj_bhakre


Tuesday, 15 February 2022

Context Task

 

The above UI is Context Task. In this example we have four components and one context store. Home is parent component and all other i.e personal, login & address are child components. In Home component we will call api and fetch user details, That user information we will store in context and then wherever it is required we will use that data from context. 

1) Home Component

import React from "react";
import PersonalDetails from "./PersonalDetails";
import Address from "./Address";
import Login from "./Login";
import axios from "axios";
import myContext from "./ContextTask";

class Home extends React.Component {
    constructor(props) {
      super(props)
    
      this.state = {
        userData: []
      }
    }

    componentDidMount(){
        axios.get('https://randomuser.me/api/?results=1').then((res)=>{
            console.log(res.data.results);
            this.setState({
                userData:res.data.results
            })
        },()=>{
            alert('Error while fetching the data');
        })
    }

    
  render() {
    return (
      <div className="container mt-5">
        <div className="row">
          <div className="col">
            <div className="card">
              <div className="row">
                <div className="col-4">
                  <img src={this.state.userData.length >0 ? this.state.userData[0].picture.medium : ""} 
                  alt="Burger" height="500px" width="100%"/>
                </div>
                <myContext.Provider value={this.state.userData}>
                <div className="col-8">
                  <div className="row">
                    <div className="col">
                      <PersonalDetails />
                    </div>
                  </div>
                  <div className="row mt-5">
                    <div className="col-6">
                        <Address/>
                    </div>
                    <div className="col-6">
                        <Login/>
                    </div>
                  </div>
                </div>
                </myContext.Provider>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export default Home;

2) Create Context Store

import React from "react";
var myContext = React.createContext();
export default myContext;

3) Address Component

import React, { Component } from 'react';
import Table from './Table';
import myContext from './ContextTask';

 class Address extends Component {
   constructor(props) {
     super(props)
   
     this.state = {
        header:['City','State','Country']
     }
   }
   
    render() {
        return (
          <div className="container">
          <div className="row">
            <div className="col">
              <div className="card">
                  <div className="card-header">
                      <h2>Address</h2>
                  </div>
                  <div className="card-body">
                   <myContext.Consumer>
                     {(contextData)=>{
                       console.log(contextData)
                       return  contextData.length > 0 ?
                       <Table header={this.state.header} 
                         data = {[contextData[0].location.city,contextData[0].location.state,contextData[0].location.country]}
                       /> : <div></div>
                     }}
                   </myContext.Consumer>
                  </div>
              </div>
            </div>
          </div>
        </div>
        );
      }
}
export default Address;

4) Login Component

import React, { Component } from 'react';
import Table from './Table';
import myContext from './ContextTask';

 class Login extends Component {
  constructor(props) {
    super(props)
  
    this.state = {
       header:['UserName','Password']
    }
  }
    render() {
        return (
            <div className="container">
            <div className="row">
              <div className="col">
                <div className="card">
                    <div className="card-header">
                        <h2>Login</h2>
                    </div>
                    <div className="card-body">
                      <myContext.Consumer>
                        {(contextData)=>{
                          return contextData.length > 0 ? 
                          <Table header={this.state.header} 
                            data= {[contextData[0].login.username,contextData[0].login.password]}
                          />
                          : 
                          <div></div>
                        }}
                      </myContext.Consumer>
                    </div>
                </div>
              </div>
            </div>
          </div>
        );
      }
}

export default Login;

5) In Every component we required table to show the data. So instead of writing table code for each component , its better to write separate component for table and use that table code in each component 

import React, { Component } from 'react';

 class Table extends Component {
  render() {
    return <div className='container'>
        <div className='row'>
            <div className='col'>
               <table className='table table-hover'>
                   <thead>
                       <tr>
                       {
                           this.props.header.map((element)=>{
                               return <th>{element}</th>
                           })
                       }
                       </tr>
                   </thead>
                   <tbody>
                       <tr>
                           {
                               this.props.data.map((ele)=>{
                                   return <td>{ele}</td>
                               })
                           }
                       </tr>
                   </tbody>
               </table>
            </div>
        </div>
    </div>;
  }
}
export default Table;



Posted By : pankaj_bhakre

Thursday, 10 February 2022

Context Example

 Requirements: We have hierarchy of components in parent-child relationship. A, B, C, D are components .A is parent of B, B is parent of C, C is parent of D. We have to send data from A to D 

Step1: Create All components A.js, B.js, C.js, D.js in proper hierarchy.

Step2: Create Context.js file & write the following code.

import React from 'react';   

var myContext = React.createContext();   // To create the context

export default myContext;

Step3: Write Following code in A.js

import React, { Component } from "react";
import B from "./B";
import myContext from "./ContextAPI";

class A extends Component {
  constructor(props) {
    super(props);

    this.state = {
      name: "Pankaj",
      city: "Mumbai",
    };
  }

  render() {
    return (
      <div className="container mt-5">
        <div className="row">
          <div className="col">
            <div className="card">
              <div className="card-header bg-dark text-white">
                <h2>A Component</h2>
              </div>
              <div className="card-body">
                <myContext.Provider value={this.state}>
                  <B />
                </myContext.Provider>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }
}
export default A;

Step4: Write following code in B.js

import React, { Component } from "react";
import C from "./C";

class B extends Component {
  render() {
    return (
      <div className="container">
        <div className="row">
          <div className="col">
            <div className="card">
              <div className="card-header bg-primary text-white">
                <h2>B Component</h2>
              </div>
              <div className="card-body">
                <C />
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }
}
export default B;

Step5: Write following code in C.js

import React, { Component } from "react";
import D from "./D";

class C extends Component {
  render() {
    return (
      <div className="container">
        <div className="row">
          <div className="col">
            <div className="card">
              <div className="card-header bg-secondary text-white">
                <h2>C Component</h2>
              </div>
              <div className="card-body">
                <D />
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }
}
export default C;

Step6: Write following code in D.js

import React, { Component } from "react";
import myContext from "./ContextAPI";

class D extends Component {
  render() {
    return (
      <div className="container">
        <div className="row">
          <div className="col">
            <div className="card">
              <div className="card-header bg-info text-white">
                <h2>D Component</h2>
              </div>
              <div className="card-body">
                <myContext.Consumer>
                  {(data) => {
                    return (
                      <div>
                        <p>{data.name}</p>
                        <p>{data.city}</p>
                      </div>
                    );
                  }}
                </myContext.Consumer>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }
}
export default D;

Tuesday, 1 February 2022

Chapter6- Context API

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

In a typical React application, data is passed top-down (parent to child) via props, but such usage can be cumbersome for certain types of props  that are required by many components within an application. Context provides a way to share values like these between components without having to explicitly pass a prop through every level of the tree.


Steps To use Context

👉Create Context object 
      • Create Context.js file import it from react
      • Use React.createContext() . This will return one object so collect it in some variable
      •  So Write this code 
                    var myContext = React.createContext(); 
                    export default Context

👉Provide Context object to parent component;
            This means import Context.js file in Parent component 
👉Provide context object to all children of parent comp using Provider component
            In order to make context object available to all children , wrapped the  immediate children                    selector inside the provider component. say B component is child component then 
             <myContext.Provider>
                <B/>
            </myContext.Provider>

👉Store the data in context object using value props
            To store the data in the context object , Provider will take one props called as value, so pass your state value values to value props 
            <myContext.Provider   value = {this.state}>
                <B/>
            </myContext.Provider>
        
👉Consume required data in child component using Consumer component

        Import context object where we want to consume data.
        Just Like Provider component , we have Consumer component to consume the data
        use  Consumer component like below code. 
         This consumer component takes data from context object & pass it to the first arguments in the                functions. Now call required state data of parent using this 'data' e.g. {data.name} 
          <myContext.Consumer>
                            {
                                    (data) => { 
                                                    <div><p>{data.name}</p></div>
                                                }
                                }
            </myContext.Consumer>


Advantages of Context API
  1. While props drilling technique if some mistakes happen while passing props , data wont receive the last child 
  2. Also if tree structure of components are there, middle components don't required the pros value so in this case we can use Context technique

PostedBy: pankaj_bhakre