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