Saturday, August 21, 2021

Basics of Form Handling Class Component

Class Form


 import React, { Component } from 'react';

import ReactDOM from 'react-dom';
 
export default class Welcome extends Component{
  constructor(props){
    super(props);
    this.state = {
      username:'',
      address:'',
      topic:''
    }
  }
  handleusername=(e=>{
this.setState({
  username:e.target.value
})
  }

handleaddress=(e=>{
this.setState({
address:e.target.value
})
}

handletopic=(e=>{
  this.setState({
    topic:e.target.value
  })
    }

    handleSubmit=(e)=>{
      alert(`${this.state.username} ${this.state.address} ${this.state.topic}`);
     e.preventDefault()
     console.warn(this.state.username)
    }

render(){
  return(
    <>
    <form onSubmit={this.handleSubmit}>
      <div>
      <label>User name</label>
      <input value={this.state.username} type="text" onChange={this.handleusername}/>
      </div>
      
      <div>
      <label>Address</label>
      <input value={this.state.address} type="text" onChange={this.handleaddress}/>
      </div>

      <div>
      <label>Topic</label>
 
 <select value={this.state.value} onChange={this.handletopic}> 
   <option value="Html">Html</option>
   <option value="CSS">CSS</option>
   <option value="Angulr">Angular</option>
 </select>
 
       </div>

<button type="submit">Submit</button>
    </form>
     </>
  )
}
}

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



Sunday, May 30, 2021

React JS Basic User Form master

 import React, { Component } from 'react'


class Form extends Component {
    constructor(props) {
        super(props)

        this.state = {
            firstName: "",
            lastName: "",
            password: "",
            gender: "",


        }
        this.handleSubmit=this.handleSubmit.bind(this)
    }

    firsthandler = (event=> {
        this.setState({
            firstName: event.target.value
        })
    }
    lasthandler = (event=> {
        this.setState({
            lastName: event.target.value
        })
    }
    passwordhandler = (event=> {
        this.setState({
            password: event.target.value
        })
    }

    genderhandler = (event=> {
        this.setState({
            gender: event.target.value
        })
    }

    handleSubmit = (event=> {
        alert(`${this.state.firstName} ${this.state.lastName}  Registered Successfully !!!!`)
        console.log(this.state);
        this.setState({
            firstName: "",
            lastName: "",
            password: '',
            gender: "",
        })
     event.preventDefault()
        
    }

    render() {
        return (
            <div>

                <form onSubmit={this.handleSubmit}>
                    <h1>User Registration</h1>
                    <label>FirstName :</label> <input type="text" value={this.state.firstName} onChange={this.firsthandler} placeholder="FirstName..." /><br />
                    <label>LastName :</label> <input type="text" value={this.state.lastName} onChange={this.lasthandler} placeholder="LastName..." /><br />
                    <label>Password :</label> <input type="password" value={this.state.password} onChange={this.passwordhandler} placeholder="Password..." /><br />
                    <label>Gender :</label><select onChange={this.genderhandler} defaultValue="Select Gender">
                        <option defaultValue>Select Gender</option>
                        <option value="male">Male</option>
                        <option value="female">Female</option>
                    </select><br />
                    <input type="submit" value="Submit" />
                </form>

            </div>
            
        )
    }
}

export default Form

React (function) Fetch Data From An API With React Hooks | AJAX and APIs

 


import React, { useState, useEffect } from "react";

const Planets = () => {
  const [hasError, setErrors= useState(false);
  const [planets, setPlanets= useState({});

  useEffect(() => {
    async function fetchData() {
      const res = await fetch("https://jsonplaceholder.typicode.com/posts");
      res
        .json()
        .then(res => setPlanets(res))
        .catch(err => setErrors(err));
    }

    fetchData();
  });

  return (
    <>
     {JSON.stringify(planets)}
      <hr/>
      <span>Has error: {JSON.stringify(hasError)}</span>
    </>
  )
}
export default Planets;

React (Class ) Fetch Data From An API With React Hooks | AJAX and APIs

 


import React, { Component } from "react";

export default class Planets extends Component {
  state = {
    hasErrors: false,
    planets: {}
  };

  componentDidMount() {
    fetch("https://jsonplaceholder.typicode.com/posts"
      .then(res => res.json())
      .then(res => this.setState({ planets: res }))
      .catch(() => this.setState({ hasErrors: true }));
  }

  render() {
    return <div>{JSON.stringify(this.state.planets)}</div>;
  }
}

React js Call API(Fetch API Data)

 import React, { Component } from 'react';

import './App.css';

class App extends Component{
  constructor(){
    super();
    this.state={
      users:null
    }}
    componentDidMount()
    {
      fetch('https://reqres.in/api/users').then((resp)=>{
        resp.json().then((result)=>{
       console.warn(result.data)
       this.setState({users:result.data})
        });
      })
   } 
 
render(){
  return(
    <div>
      <h1>Fetch API Data</h1>
    
    {
      this.state.users ?
      this.state.users.map((item,i=>
     <div>{i} --- {item.first_name} --- {item.last_name} --- {item.email}</div>
      )
      :
      null
    }
   
    </div>

  )}
}




export default App;

Important things in ReactJs - Keys - Fragments - List

 import React from 'react';

import './App.css';

const Listdata = [
  {
  name:"Ujjwal Tripathi"
},
{
  name:"Pushpendra Tripathi"
},
{
  name:"Tripti Tripathi"
},
]

const List = () =>{
return Listdata.map((val,index)=>{
  return<li key={index}>{val.name}</li>
});
}
 
const Biodata = () =>{
  return(
    <>
      <p>Name - Jonson</p>
      <p>Address - USA</p>
    </>
  )
}
function App() {
return (
<div>
  <List/>
<Biodata/>
</div>    
  );}
export default App;

ReactJs Forms (1)

import React from 'react';

const App = () => {
  const [fields,setFeilds]= React.useState({});
  const [errors,setErrors]= React.useState({});

  const validate = () =>{
    let is_error = false;
    let error_list = {};

    if(!fields.name){
      error_list.name = 'please enter the name';
      is_error = true;
    }
    if(!fields.age){
      error_list.age = 'please enter the age';
      is_error = true;
    }
    if(!fields.city){
      error_list.city = 'please select the city';
      is_error = true;
    }
    if(!fields.address){
      error_list.address = 'please enter the address';
      is_error = true;
    }

    if(is_error){
      setErrors(error_list);
      return true;
    }
    return false;
  }

  const handleChange = (event=>{
    setFeilds({...fields,[event.target.name]:event.target.value});
    validate();
    //console.log(event.target.value);
  }

  const handleSubmit = (event)=>{
    event.preventDefault();

    if(validate()){
      console.log(errors);
    }else{
      console.log('submitted!');
    }


  }

  return (
    <div className="container" >
      <h1 >React Forms</h1>
      <form onSubmit={handleSubmit}>
        <p>
          Name : <br /><input type="text" name="name" onChange={handleChange} />
        </p>
        {errors.name && (<p className="error">{errors.name}</p>)}
        <p>
          Age : <br /><input type="text" name="age" onChange={handleChange}/>
        </p>
        {errors.age && (<p className="error">{errors.age}</p>)}
        <p>
          Address : <br /><input type="text" name="address" onChange={handleChange}/>
        </p>
        {errors.address && (<p className="error">{errors.address}</p>)}
        <p>
          City :<br />
          <select name="city" onChange={handleChange}>
            <option></option>
            <option>Noida</option>
            <option >Delhi</option>
            <option>Chandigarh</option>
          </select>
        </p>
        {errors.city && (<p className="error">{errors.city}</p>)}
        <p>
          Gender :<br />
          <input type="radio" id="male" name="gender" value="male"  onChange={handleChange}/>{" "}
          <label htmlFor="male">male</label>
          <input type="radio" id="female" name="gender" value="female" onChange={handleChange}/>{" "}
          <label htmlFor="female">female</label>
        </p>



        <p>
          Message:
          <br />
          <textarea name="about" onChange={handleChange} ></textarea>
        </p>
        <p>
          <input
            type="checkbox"
            name="confirm"
            id="confirm"
            onChange={handleChange}
          />{" "}
          <label htmlFor="confirm">please confirm </label>
        </p>
        <p>
          <input type="submit" name="save" value="save" />
        </p>
      </form>

      {JSON.stringify(fields)}
    </div >
  )
}

export default App;


Sunday, May 2, 2021

Node Express Route Params

var express = require('express');
var app = express();

app.get('/',function(req,res){
res.send("This is the Home Page");
});

app.get('/about',function(req,res){
res.send("This is the About Us Page");
});
app.get('/contact',function(req,res){
res.send("This is the Contact Us Page");
});

app.get('/profile/:name',function(req,res){
    res.send('You requested to see a profile with a name of'+req.params.name);
    });
   

app.listen(4000) 


Install-

npm i express

Serving JSON Data

 

var http =require('http');
var fs = require('fs');
var server = http.createServer(function(req,res){
console.log('request was made:' + req.url);
res.writeHead(200, {'Content-Type':'application/json'});
var myObj ={
name:'Ujjwal',
job:'Front End Developer',
age:40
};
res.end(JSON.stringify(myObj));
});
server.listen(3000,'127.0.0.1')
console.log("port 3000")



var http =require('http');
var fs = require('fs');
var server = http.createServer(function(req,res){
console.log('request was made:' + req.url);
res.writeHead(200, {'Content-Type':'text/json'});
var myObj ={
name:'Ujjwal',
job:'Front End Developer',
age:40
};
res.end(JSON.stringify(myObj));
});
server.listen(3000,'127.0.0.1')
console.log("port 3000")

Fetching JSON data from REST APIs

data.json---------------------------------- [     {     "userId" : 1 ,     "id" : 1 ,     "title" : "sunt...