Thursday, 12 May 2022

Step by Step example on redux flow

 Requirements: 

Create two different components inside card. Component 1 is home component and component 2 is Name comp. Home comp having input text field with button name called Send. If user type in the text field and click on send button then in Name component same text field should appear.


Step1: Create Home component with following code.

import React, { Component } from 'react';

import Name from '../Name/Name.js';

import nameAction from '../../Actions/NameAction.js';


 class Home extends Component {

    constructor(props){

      super();

      this.state = {

        name: ''

      }

    }

    sendDataToAction=()=>{

      nameAction(this.state.name);

    }

  render() {

    return (

      <div className='container mt-5'>

          <div className='col'>

                <div className='card'>

                    <div className='card-header'>

                        <input type="text" onChange= {(e)=>{

                          this.setState({

                            name:e.target.value

                          })

                        }}/>

                        <button  className='btn btn-primary m-3' onClick={this.sendDataToAction}>Send</button>

                    </div>

                    <div className='card-body'>

                        <Name/>

                    </div>

                </div>

          </div>

      </div>

    )

  }

}

export default Home

 Step2: Create Name component with following code

import React, { Component } from 'react';

import {connect} from 'react-redux';


 class Name extends Component {

  render() {

    return (

      <div className='container mt-5'>

         <div className='row'>

         <div className='col'>

                <p className='display-5'>{this.props.storeData}</p>

          </div>

         </div>

      </div>

    )

  }

}

export default connect((storeData)=>{

  return {

    storeData: storeData.nameReducer.name,

  };

},null)(Name)

Step3: Create store with following code

import {createStore, combineReducers, applyMiddleware} from 'redux';
import logger from 'redux-logger'
import cityReducer from '../Reducer/CityReducer';
import nameReducer from '../Reducer/NameReducer';

 const cR =  combineReducers({
    nameReducer,
    cityReducer
})

 const myStore = createStore(cR, applyMiddleware(logger));


 export default myStore;

Step4: Create Reducers with following code

import userData from "../InitialData/InitialData"
const nameReducer = (state=userData, action) => {
    switch(action.type){

        case 'NAME':{
            state = {
                ...state,
                name:action.payLoad,
            }
        }
    }
    return state
}

export default nameReducer

Step5: Create initialdata 

var userData = {
    user : ''
}

export default userData



Important packages to be installed while redux pattern

1) npm install redux
it allows us to use  redux library

2)npm install react-redux 
It will give us provider component which is used to wrap the app component in index.js

3)  npm in redux-logger
It is used for developer to see the whats is there in store.

Redux

 Redux is an open-source JavaScript library for managing and centralizing application state. It is most commonly used with libraries such as React or Angular for building user interfaces. Redux is the official  UI binding library for React. If you are using Redux and React together, you should also use React Redux to bind these two libraries..

Redux: Redux is 3rd party library used for state management in the application. State management refers to deal with

data management. i.e. sharing the data between one component to another.

We have lot of techniques for sharing the data between components like 

props --- Used for transferring data from Parent to child only

callbacks  --- Used for transferring data from child to parent only

context API  --- Used for transferring data from Parent to child only


To overcome the above drawbacks , we have new concept called Redux. React did not introduced the redux concept whereas its 3rd party library.




How to implement Redux.

1) Create React app using react library
2) Create Redux store using redux library
3) To store the data from react app to redux store we can not do it directly
4) There is one special function called reducer , once the data avaliable to reducer then redux store will take it from reducer.
5)But component can not store data directly to reducer so there is one more function called Action. So component first store the data into Action then From Action it will goes to dispatch function and from dispatch it will gors to reducer.


To Create Redux Store
1) Install redux using npm install redux
2) using createStore() we can create redux store.
3) Make available this store to all components for that install react-redux
npm install react-redux
4) React-redux provides a compoenent called provider. 
5) We have wrap this <App/> component inside <Provider/>
6)<Provider/> component takes one default props called store

Friday, 29 April 2022

HOC Example

 Create HOCHome class and write following code in it


import React, { Component } from "react";

import Counter from "./Counter";

import Hover from "./Hover";


class HOCHome extends Component {

  render() {

    return (

      <div className="container text-center mt-5">

        <div className="row">

          <Counter />

        </div>

        <div className="row mt-5">

          <Hover />

        </div>

      </div>

    );

  }

}

export default HOCHome;

Create HOC.js and write following code in it

import React from "react";

const hoc = (Component) => {

  class NewComponent extends React.Component {

    constructor(props) {

      super(props);

      this.state = {

        count: 0,

      };

    }

    updateCount = () => {

      this.setState({

        count: this.state.count + 1,

      });

    };

    render() {

      return (

        <Component count={this.state.count} updateCount={this.updateCount} />

      );

    }

  }

  return NewComponent;

};

export default hoc;

Create Counter.js and write following code in it

import React, { Component } from "react";

import hoc from "./HOC";


class Counter extends Component {

  render() {

    return (

      <div className="container">

        <p className="display-6">Clicked me {this.props.count} times</p>

        <button className="btn btn-primary" onClick={this.props.updateCount}>

          Update Count

        </button>

      </div>

    );

  }

}

export default hoc(Counter);

Create Hover.js and write following code in it

import React, { Component } from "react";

import hoc from "./HOC";


class Hover extends Component {

  render() {

    return (

      <div className="container">

        <p className="display-6 lead" onMouseOver={this.props.updateCount}>

          Hovered me {this.props.count} times

        </p>

      </div>

    );

  }

}

export default hoc(Hover);

Wednesday, 20 April 2022

Topic Wise Questions & Answers

 ➤ Basic UI/UX & Web Development

➤ HTML 

➤ CSS

➤ Java-Script


Basic UI/UX Questions

 1) Software application and software product : 

➢ A Software that is designed according to client requirements is known as “Application”. 

➢ A Software designed according to market requirements is known as “Software product”. 

Example : IRCTC - Application MS Office - Product


2) Types Of Applications and Products :

  • Desktop :It is a stand alone application that is installed and used in the business with less user base and no remote access. 
  • Web Application: It is an internet based application used for business with large user base and remote access.
  • Distributed :A Distribute technology allows applications running on two different machines to share info between them.
  • Gaming: It is a 2D and 3D graphics application supported to game consoles like X-Box. 
  • Mobile: It is a mobile relative application that runs on android, IOS and Windows. 
  • AI: It is an Artificial Intelligence application that enables automation and robotics.
  • IOT: It refers to Internet Of Things, which is an embedded technology that allows remote access.
3)What Is UI ? 
➢ A Software application handles various functionalities according to the business requirements. The Functionalities are designed by using different technologies.
 ➢ The user requires special skills in handling an application designs with specific technology. Hence we provide a user friendly interface so that users can easily interact with application. It is often known as “UI”

4)What Is UX ? 
➢ UX in software application refers to user experience. 
➢ The modern applications require more UX along with the UI. 
➢ The challenges with UX in modern web applications are (a) Fluid UX (b) Unified UX 
➢ The Fluid UX enables an application to load every content on to single page. The new details are updated page. The new details are updated without reloading the page. 
➢ The Unified UX provider same experience for application across any device i.e from a mobile to browser. 

5)What are Progressive Applications ? 
A: Progressive application will provide app like experience even on a browser.

6) Network : A Computer network comprises of group of computers connecting with each other for sharing info and resources. 
7) Types of Networks : The Computer networks are categorized into 3 major types - i. LAN ( Local Area Network ) ii. MAN ( Metropolitan Area Network ) iii. WAN ( Wide Area Network )
8) Internet : It resembles a wide area network that connects computer across the world.
9)Web :  Web is a portion of internet with restricted access.  Tim Berner’s Lee introduced web in 1990.  It uses a network mechanism where client sends request and server send response. The standards of web are maintained by W3C ( World Wide Web Consortium ).

10)Web Page : Web page is a hyper text document that provide an UI for website. It allows the user to view,access and interact with resources in a website. 
 The web pages are categorized in to 2 types 1. Static Page 2. Dynamic Page

11)Static Page
➢ The term static refers to continuous memory. 
➢ The memory allocated for the first request the same memory will be used across other requests. 
➢ A static page contains same information to display across any no.of requests and clients. 
➢ The static pages are designed by using HTML, CSS, and Client side script. 
➢ A static page have two extensions .html, .htm. Example : home.html, about.htm

12)Dynamic Page
➢ The term dynamic refers to non static memory. 
➢ It is a discrete memory i.e, memory is newly allocated for every request. 
➢ A dynamic page contains information that change according to client requests, it generates a response customized for every request. 
➢ The dynamic pages are designed by using server side technologies like JSP, PHP, ASP etc, 
➢ They have the extension like .jsp, .asp, .php, .aspx. Example : results.jsp, movies.aspx, ticket.php.

13)Web application : A Web application provides an UI from where user can interact with the business. It requires server side technologies like JSP, PHP, ASP etc.

14)Web debugger : It is a software tool used to track the performance of any page (or) application. Every browser have a debugger which you can invoke by using F12 function key. Example : fiddler, post man etc.,

15) Api’s :Api is a service provided by third party sources which you can integrate in to any application to provide a specific functionality. Example : google maps api, facebook login api, captcha api etc.,

16) URL and URI : ➢ URL is the virtual path generated by a web server and used by clients in order to access the resources from a website. 
➢ It is a uniform resource locator. 
➢ The URI is an identifier used to access any specific location within the resource. URL ↑ http://www.amazon.in/electronic.jsp#mobiles ↓ ↓ ↓ Protocol Domain URI

17)Protocol : A protocol defines a set of rules that are used by computers in network to communicate with each other. The popular protocols are - http, https, ftp, file, ttp/ip, msmq, named pipes, smtp etc., http - Hyper text transfer protocol - web https - secured http - web ftp/file - file transfer protocol - intranet Smtp - simple mail transfer protocol - email

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

Monday, 31 January 2022

Routing Example

Create Nav.js component and write following code in it 

import React, { Component } from 'react';

import {Link} from 'react-router-dom'


 class Nav extends Component {

  render() {

    return <nav className='navbar navbar-dark bg-primary'>

        <div className='container'>

            <Link to="/" className='navbar-brand'>

                Home

            </Link>

            <ul className='nav'>

                <li className='nav-item'>

                <Link to='/home' className='nav-link text-white'>

                Axios

            </Link>

                </li>

                <li className='nav-item'>

                <Link to='/chatapp' className='nav-link text-white'>

                ChatApp

            </Link>

                </li>

                <li className='nav-item'>

                <Link to='/profile' className='nav-link text-white'>

                UserProfile

            </Link>

                </li>

                <li className='nav-item'>

                <Link to='/gender' className='nav-link text-white'>

                FilterApp

            </Link>

                </li>

            </ul>

        </div>

    </nav>;

  }

}

export default Nav;


Update App.js with following code.

import './App.css';

import State from './Components/Header/Header.js';

import Home from './Components/ChatApp/Home';

import ProfileState from './Components/State/ProfileState';

import Gender from './Components/Gender/Gender';

import AsyncAwait from './Components/Axios/AsyncAwait';

import Nav from './Components/Nav/Nav';

import { BrowserRouter, Route, Routes } from 'react-router-dom';

import PageNotFound from './Components/PageNotFound/PageNotFound';


function App() {

  return (

    <div className="App">

<BrowserRouter>

<Nav/>

<Routes>

<Route path="/" element={<State/>} />

  <Route path="/home" element={<AsyncAwait/>} />

  <Route path="/chatapp" element={<Home/>} />

  <Route path="/profile" element={<ProfileState/>} />

  <Route path="/gender" element={<Gender/>} />

<Route path="*" element={<PageNotFound />} />

</Routes>

</BrowserRouter>

    </div>

  );

}

export default App;


After this do npm start , our application will look like this



PostedBy: pankaj_bhakre


Chapter5-Routing

 React Router is a standard library for routing in React. It enables the navigation among views of various components in a React Application, allows changing the browser URL, and keeps the UI in sync with the URL.

Let us now install React Router in our Application.

Installing React Router: React Router can be installed via npm in your React application. Follow below command to install Router in your React application: npm install --save react-router-dom

 Adding React Router Components: The main Components of React Router are:

BrowserRouter: BrowserRouter is a router implementation that uses the HTML5 history API(pushState, replaceState and the popstate event) to keep your UI in sync with the URL. It is the parent component that is used to store all of the other components.

Routes: It’s a new component introduced in the v6 and a upgrade of the component. The main advantages of Routes over Switch are: Routes are chosen based on the best match instead of being traversed in order.

Route: Route is the conditionally shown component that renders some UI when its path matches the current URL.

Link: Link component is used to create links to different routes and implement navigation around the application. It works like HTML anchor tag.

To add React Router components in your application, open your project directory in the editor you use and go to app.js file. Now, add the below given code in app.js.

import {

    BrowserRouter as Router,

    Routes,

    Route,

    Link

} from 'react-router-dom';

Note: BrowserRouter is aliased as Router.


PostedBy: pankaj_bhakre

Filter the Array based on gender

 A) Using Different Methods in Radio Button

import React, { Component } from "react";

import { userData } from "./../../UserData.js";


class Gender extends Component {

  constructor(props) {

    super(props);


    this.state = {

      info: userData.results,

    };

  }



  allUsers = () => {

      this.setState({

          info: userData.results

      })

  }

  maleUsers = (event) => {

    if(event.target.value === 'Male'){

      this.filteredarray = userData.results.filter(x=>x.gender === 'male')

    this.setState({

        info:this.filteredarray

    })

    }

    

    console.log(userData.results.filter(x=>x.gender === 'male'));

}


femaleUsers = (event) => {

 if(event.target.value === 'Female'){

  this.filteredarray = userData.results.filter(x=>x.gender === 'female')

  this.setState({

      info:this.filteredarray

  })

 }

  console.log(userData.results.filter(x=>x.gender === 'female'));

}

  render() {

    return (

      <div className="container">

        <div className="row">

          <div className="col mt-5  bg-success text-white">

            <h2>Filter Users list based on Gender </h2>

          </div>

        </div>

        <div className="row mt-5">

            <div className="col-2">

            <input type="radio" value="Other" name="gender"   onChange={this.allUsers} /> All

            </div>

            <div className="col-2">

            <input type="radio" value="Male" name="gender"  onChange={this.maleUsers}/> Male

            </div>

            <div className="col-2">

            <input type="radio" value="Female" name="gender"  onChange={this.femaleUsers}/> Female

            </div>

        </div>

        <div className="row">

          <div className="col mt-5 p-3">

            <table className="table table-hover">

              <thead className="bg-dark text-white">

                <tr>

                  <th>Image</th>

                  <th>Name</th>

                  <th>Gender</th>

                  <th>Email</th>

                  <th>City</th>

                </tr>

              </thead>

              <tbody>

                {this.state.info.map(function (element) {

                  return (

                    <tr>

                      <td>

                        {

                          <img

                            src={element.picture.medium}

                            className="img-fluid"

                            alt="userPicture"

                          ></img>

                        }

                      </td>

                      <td>

                        {element.name.first} {element.name.last}

                      </td>

                      <td>{element.gender}</td>

                      <td>{element.email}</td>

                      <td>{element.location.city}</td>

                    </tr>

                  );

                })}

              </tbody>

            </table>

          </div>

        </div>

      </div>

    );

  }

}

export default Gender; 

 B) Using Switch statement & single Method in Radio Button

filteredUsers = (event) => {

    switch(event.target.value){

      case "Male": 

      this.filteredarray = userData.results.filter(x=>x.gender === 'male');

      this.setState({

        info:this.filteredarray

      });

      break;

      case 'Female': 

      this.filteredarray = userData.results.filter(x=>x.gender === 'female');

      this.setState({

        info:this.filteredarray

      });

      break;

      default:

        this.setState({

          info:userData.results

        });

    }

  }

A) Using if-else statement & single Method in Radio Button

filteredUsers = (event) => {

    if(event.target.value === 'Male'){

      this.filteredarray = userData.results.filter(x=>x.gender === 'male');

      this.setState({

        info:this.filteredarray

      });

    }else if (event.target.value === 'Female'){

      this.filteredarray = userData.results.filter(x=>x.gender === 'female');

      this.setState({

        info:this.filteredarray

      });

    } else{

      this.setState({

        info:userData.results

      });

    }

  }


PostedBy: pankaj_bhakre

Sunday, 30 January 2022

Fetching data from fake api using Axios library using map function & Ternary conditions.(using async-await)

import React, { Component } from 'react';

import axios from 'axios';


 class AsyncAwait extends Component {

     constructor(props) {

       super(props)

     

       this.state = {

        userInfo: []

       }

      // this.getUserData = this.getUserData.bind(this);  

     }


      getUserData = async () => {

        const result =   await  axios.get("https://jsonplaceholder.typicode.com/users")

        console.log(result.data);

        this.setState({

            userInfo:result.data

        });

        }


    // async getUserData() {

    //  const result =   await  axios.get("https://jsonplaceholder.typicode.com/users")

    //  console.log(result.data);

    //  this.setState({

    //      userInfo:result.data

    //  });

    //  }

     

  render() {

    return (

        <div className="container">

          <div className="row mt-5">

            <div className="col">

              <button className="btn btn-primary" onClick={this.getUserData}>

                Get Data

              </button>

            </div>

          </div>

              { this.state.userInfo.length > 0 ? (

                  <div className="row">

          <div className="col">

                <table className="table">

                  <thead>

                    <tr>

                      <th>ID</th>

                      <th>NAME</th>

                      <th>EMAIL</th>

                      <th>CITY</th>

                      <th>PHONE</th>

                      <th>COMPANY_NAME</th>

                    </tr>

                  </thead>

                  <tbody>

                    {this.state.userInfo.map(function (element, index) {

                      return (

                        <tr>

                          <td>{element.id}</td>

                          <td>{element.name}</td>

                          <td>{element.email}</td>

                          <td>{element.address.city}</td>

                          <td>{element.phone}</td>

                          <td>{element.company.name}</td>

                        </tr>

                      );

                    })}

                  </tbody>

                </table>

              </div>

          </div>

              ) : (

                  <div className="text-danger row mt-5">

              <h2> Data is not Available</h2>

            </div>

              )      

              }

        </div>

      );

  }

}

export default AsyncAwait; 

Fetching data from fake api using Axios library using map function & Ternary conditions.(using then)

 import React, { Component } from "react";

import Axios from "axios";


class AxiosUser extends Component {

  constructor(props) {

    super(props);


    this.state = {

      userInfo: [],

    };

  }


  getUserData = () => {

    Axios.get("https://jsonplaceholder.typicode.com/users").then(

      (result) => {

        console.log(result.data);

        this.setState({

            userInfo:result.data

        })

      },

      (error) => {

        console.log(error);

      }

    );

  };


  render() {

    return (

      <div className="container">

        <div className="row mt-5">

          <div className="col">

            <button className="btn btn-primary" onClick={this.getUserData}>

              Get Data

            </button>

          </div>

        </div>

            { this.state.userInfo.length > 0 ? (

                <div className="row">

        <div className="col">

              <table className="table">

                <thead>

                  <tr>

                    <th>ID</th>

                    <th>NAME</th>

                    <th>EMAIL</th>

                    <th>CITY</th>

                    <th>PHONE</th>

                    <th>COMPANY_NAME</th>

                  </tr>

                </thead>

                <tbody>

                  {this.state.userInfo.map(function (element, index) {

                    return (

                      <tr>

                        <td>{element.id}</td>

                        <td>{element.name}</td>

                        <td>{element.email}</td>

                        <td>{element.address.city}</td>

                        <td>{element.phone}</td>

                        <td>{element.company.name}</td>

                      </tr>

                    );

                  })}

                </tbody>

              </table>

            </div>

        </div>

            ) : (

                <div className="text-danger row mt-5">

            <h2> Data is not Available</h2>

          </div>

            )

                

            }

      </div>

    );

  }

}

export default AxiosUser;


PostedBy: pankaj_bhakre

Class component with fetching data from fake api using Axios library

 import React, { Component } from 'react';

import Axios from 'axios';


 class AxiosUser extends Component {

     getUserData=()=>{

        Axios.get("https://jsonplaceholder.typicode.com/users").then(result => {

            console.log(result.data);

        }, 

          (error) => {

              console.log(error);

          }

        )

     }

     

  render() {

    return <div className='container'>

        <div className='row mt-5'>

            <div className='col'>

                <button className='btn btn-primary' onClick={this.getUserData}>Get Data</button>

            </div>

        </div>

    </div>;

  }

}

export default AxiosUser;


PostedBy: pankaj_bhakre

Chapter4-Axios Library

 Introduction to Axios: Axios, which is a popular library is mainly used to send asynchronous HTTP requests to REST endpoints. This library is very useful to perform CRUD operations.

  • This popular library is used to communicate with the backend.
  •  Axios supports the Promise API, native to JS ES6.
  • Using Axios we make API requests in our application. Once the request is made we get the data in Return, and then we use this data in our project. 

Install Axios library using the command given below…

npm install axios

After Axios installation, you can import this library into your file and use it to make an HTTP request. 

Axios.get("https://jsonplaceholder.typicode.com/users").then(result => {
            console.log(result.data);
        },

Axios provides different methods for CRUD operation like 
get() ---- to fetch data
post()---- to submit data
put() ---- to update data
delete() --- to delete data



PostedBy: pankaj_bhakre  

Saturday, 29 January 2022

Class component fetching data from another file

Create UserData.js & Emp.js file write following code init.

UserData.js

export var userData ={

              results: [{

                             "gender": "female",

                             "name": {

                                           "title": "Mrs",

                                           "first": "Lola",

                                           "last": "Obrien"

                             },

                             "location": {

                                           "street": {

                                                          "number": 5836,

                                                          "name": "Rectory Lane"

                                           },

                                           "city": "Inverness",

                                           "state": "Cornwall",

                                           "country": "United Kingdom",

                                           "postcode": "A8 8XT",

                                           "coordinates": {

                                                          "latitude": "6.1567",

                                                          "longitude": "102.7246"

                                           },

                                           "timezone": {

                                                          "offset": "+9:00",

                                                          "description": "Tokyo, Seoul, Osaka, Sapporo, Yakutsk"

                                           }

                             },

                             "email": "lola.obrien@example.com",

                             "login": {

                                           "uuid": "aa6e9b62-c732-4947-963c-94eaf7b46cef",

                                           "username": "silverlion377",

                                           "password": "clemson",

                                           "salt": "CmkMqCgy",

                                           "md5": "306ab007e07b3cf978b587aa0d32d4e7",

                                           "sha1": "528a2a36f1af754ecd4527fe44d59b36458ab7e3",

                                           "sha256": "bac99827e558efa75264fda16d7f579f1129b074ee95c6d057dc7430ab65b6b4"

                             },

                             "dob": {

                                           "date": "1994-03-22T14:00:21.714Z",

                                           "age": 28

                             },

                             "registered": {

                                           "date": "2013-07-30T16:26:22.869Z",

                                           "age": 9

                             },

                             "phone": "016977 90968",

                             "cell": "0794-864-054",

                             "id": {

                                           "name": "NINO",

                                           "value": "JR 46 06 00 D"

                             },

                             "picture": {

                                           "large": "https://randomuser.me/api/portraits/women/92.jpg",

                                           "medium": "https://randomuser.me/api/portraits/med/women/92.jpg",

                                           "thumbnail": "https://randomuser.me/api/portraits/thumb/women/92.jpg"

                             },

                             "nat": "GB"

              }, {

                             "gender": "female",

                             "name": {

                                           "title": "Mrs",

                                           "first": "Frida",

                                           "last": "Møller"

                             },

                             "location": {

                                           "street": {

                                                          "number": 6875,

                                                          "name": "Mejsevej"

                                           },

                                           "city": "Branderup J",

                                           "state": "Syddanmark",

                                           "country": "Denmark",

                                           "postcode": 22903,

                                           "coordinates": {

                                                          "latitude": "2.7742",

                                                          "longitude": "79.5760"

                                           },

                                           "timezone": {

                                                          "offset": "-10:00",

                                                          "description": "Hawaii"

                                           }

                             },

                             "email": "frida.moller@example.com",

                             "login": {

                                           "uuid": "dc1305fb-2dd5-42b6-bbf5-5af5f542ed7f",

                                           "username": "whiteostrich452",

                                           "password": "neville",

                                           "salt": "ubpezdUT",

                                           "md5": "b9450779c685ef5b8d62f3a4e418bab3",

                                           "sha1": "19f44bec7538d444be90bb31c4c2b0ca90f56e22",

                                           "sha256": "4ebd1df4296772e33b1c290bde677b6d48c144af420aa3ff672d6c62a9910c32"

                             },

                             "dob": {

                                           "date": "1995-02-02T01:55:00.588Z",

                                           "age": 27

                             },

                             "registered": {

                                           "date": "2011-05-18T18:24:38.738Z",

                                           "age": 11

                             },

                             "phone": "30920279",

                             "cell": "44095149",

                             "id": {

                                           "name": "CPR",

                                           "value": "020295-0777"

                             },

                             "picture": {

                                           "large": "https://randomuser.me/api/portraits/women/22.jpg",

                                           "medium": "https://randomuser.me/api/portraits/med/women/22.jpg",

                                           "thumbnail": "https://randomuser.me/api/portraits/thumb/women/22.jpg"

                             },

                             "nat": "DK"

              }],

              "info": {

                             "seed": "f340257157c1c25c",

                             "results": 2,

                             "page": 1,

                             "version": "1.3"

              }

};

 

EMP.js

export var emp = {

  results: [

    {

      gender: "male",

      name: {

        title: "Mr",

        first: "Jeremy",

        last: "Lawrence",

      },

      location: {

        street: {

          number: 2369,

          name: "Crockett St",

        },

        city: "San Mateo",

        state: "Maine",

        country: "United States",

        postcode: 90842,

        coordinates: {

          latitude: "84.9481",

          longitude: "-164.6132",

        },

        timezone: {

          offset: "+4:00",

          description: "Abu Dhabi, Muscat, Baku, Tbilisi",

        },

      },

      email: "jeremy.lawrence@example.com",

      login: {

        uuid: "78932c5e-c6ea-4fea-973e-9da2b2c3fe18",

        username: "bluetiger627",

        password: "hounddog",

        salt: "Vz6O83Of",

        md5: "ed9d2d507ed72f4880c8ce79b5f8a92a",

        sha1: "006502125b81fa1cd82fbcbf16c78efa8de64b69",

        sha256:

          "c2a4f208c9156a42d7664e8d6a9f2f077179381b509eee79275750a4c396d6d4",

      },

      dob: {

        date: "1989-01-19T11:44:19.498Z",

        age: 33,

      },

      registered: {

        date: "2013-03-11T07:32:42.850Z",

        age: 9,

      },

      phone: "(717)-299-1541",

      cell: "(671)-779-8846",

      id: {

        name: "SSN",

        value: "022-29-4928",

      },

      picture: {

        large: "https://randomuser.me/api/portraits/men/18.jpg",

        medium: "https://randomuser.me/api/portraits/med/men/18.jpg",

        thumbnail: "https://randomuser.me/api/portraits/thumb/men/18.jpg",

      },

      nat: "US",

    },

    {

      gender: "female",

      name: {

        title: "Miss",

        first: "Iolita",

        last: "Nunes",

      },

      location: {

        street: {

          number: 7178,

          name: "Rua Quatro",

        },

        city: "Teófilo Otoni",

        state: "Paraná",

        country: "Brazil",

        postcode: 50044,

        coordinates: {

          latitude: "-2.5161",

          longitude: "-125.3800",

        },

        timezone: {

          offset: "-3:30",

          description: "Newfoundland",

        },

      },

      email: "iolita.nunes@example.com",

      login: {

        uuid: "9b2bbedc-7a03-444e-bf4e-1f6b44b9e87b",

        username: "goldenswan706",

        password: "nimitz",

        salt: "STO3yKnu",

        md5: "4f8ca7d5bbaf6e4ad72a1e8f2cd3c142",

        sha1: "56ec11994f363898c7c4fada86d55494a398e74a",

        sha256:

          "1c639643d63ef4e954f9effdff3db9d89c7ed53ed6b22a5b47412d46aa21fb35",

      },

      dob: {

        date: "1952-12-20T15:24:59.373Z",

        age: 70,

      },

      registered: {

        date: "2014-11-23T04:27:30.259Z",

        age: 8,

      },

      phone: "(95) 4892-4517",

      cell: "(85) 3502-5328",

      id: {

        name: "",

        value: null,

      },

      picture: {

        large: "https://randomuser.me/api/portraits/women/67.jpg",

        medium: "https://randomuser.me/api/portraits/med/women/67.jpg",

        thumbnail: "https://randomuser.me/api/portraits/thumb/women/67.jpg",

      },

      nat: "BR",

    },

};

 

Now Create UserProfile.js write following code

import React, { Component } from "react";

import { userData } from "./../../UserData";

import { emp } from "./../../emp";

 

class UserProfile extends Component {

  constructor(props) {

    super(props);

 

    this.state = {

      info: userData,

    };

  }

 

  updateUser = () => {

    this.setState({

      info: userData,

    });

  };

 

  updateEmployee = () => {

    this.setState({

      info: emp,

    });

  };

 

  render() {

    return (

      <div className="container mt-5">

        <div className="row">

          <p className="lead">

            Lorem ipsum dolor sit amet consectetur, adipisicing elit. Odio

            excepturi sapiente praesentium, soluta officia consequatur numquam

            sed at itaque, repudiandae sint esse aliquid delectus repellat

            earum, placeat et! Sit adipisci magnam veritatis obcaecati quis

            necessitatibus, eveniet earum aut, quibusdam sequi amet minima harum

            nesciunt nihil nisi impedit nobis! Nostrum ad exercitationem rerum

            soluta quam tenetur dolor molestias, mollitia explicabo corrupti.

          </p>

        </div>

        <div className="row">

          <div className="col-4">

            <button className="btn btn-primary" onClick={this.updateUser}>

              User Information

            </button>

          </div>

          <div className="col-4">

            <button className="btn btn-success" onClick={this.updateEmployee}>

              Employee Information

            </button>

          </div>

        </div>

        <div className="row mt-5">

          <div className="col">

            <table className="table table-hover">

              <thead className="bg-dark text-white">

                <tr>

                  <th>IMAGE</th>

                  <th>NAME</th>

                  <th>GENDER</th>

                  <th>EMAIL</th>

                  <th>CITY</th>

                </tr>

              </thead>

 

              <tbody>

                {this.state.info.results.map(function (element) {

                  return (

                    <tr>

                      <td>

                        <img

                          src={element.picture.medium}

                          className="img-fluid"

                        />

                      </td>

                      <td>

                        {element.name.first} {element.name.last}

                      </td>

                      <td>{element.gender}</td>

                      <td>{element.email}</td>

                      <td>{element.location.city}</td>

                    </tr>

                  );

                })}

              </tbody>

            </table>

          </div>

        </div>

      </div>

    );

  }

}

export default UserProfile;



PostedBy: pankaj_bhakre