Saturday, November 18, 2023

Input component for reuse

 


import React from 'react'
import classes from './Input.module.css'

const Input = (props) => {
  return (
    <div className={classes.input}>
        <label htmlFor={props.input.id}>{props.label}</label>
        <input {...props.input}/>

    </div>
  )
}

export default Input
  1. Passing from below from another component where input requireed <Input
  2. label='Amount'
  3. input={{
  4. id: 'amount',
  5. type: 'number',
  6. min: '1',
  7. max: '5',
  8. step: '1',
  9. defaultValue: '1',
  10. }}
  11. />


in
in


Sunday, October 22, 2023

React reducer dispatch increment decrement button

dispatching in 2 ways 1.directly and 2 with function
++++++++++


import { useReducer,React } from 'react';
import './App.css';

const incReducer=(state,action)=>{
 
  if(action.type==="dec"){
    return {"val":state.val-1};
  }if(action.type==="inc"){
    return {"val":state.val+1};
  }
}
function App() {
  const [state,dispatch]=useReducer(incReducer,{"val":0});
const ipchangeHandler=(ty)=>{
 dispatch({"type":ty})
}

  return (
    <div>
      <button type='button' onClick={(event)=>ipchangeHandler('dec',event.target.value)}>Decrement</button>
      {state.val}
      <button type='button' onClick={()=>dispatch({"type":"inc"})}>Increment</button>
    </div>
  );
}

export default App;

=====================================
type 1 passing dispatch

   <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: "INCREMENT" })}>Increment</button>
      <button onClick={() => dispatch({ type: "DECREMENT" })}>Decrement</button>
    </div>


type 2 passing dispatch through function

   <div>
      <button type='button' onClick={(event)=>ipchangeHandler('dec',event.target.value)}>Decrement</button>
      {state.val}
      <button type='button' onClick={(event)=>ipchangeHandler('inc',event.target.value)}>Increment</button>
    </div>


  const [state,dispatch]=useReducer(incReducer,{"val":0});
const ipchangeHandler=(ty)=>{
 dispatch({"type":ty})
}



const incReducer=(state,action)=>{
 
  if(action.type==="dec"){
    return {"val":state.val-1};
  }if(action.type==="inc"){
    return {"val":state.val+1};
  }
}





 

Tuesday, December 13, 2022

React: UseEffect Dec

 const Login = (props) => {

  const [enteredEmail, setEnteredEmail] = useState('');
  const [emailIsValid, setEmailIsValid] = useState();
  const [enteredPassword, setEnteredPassword] = useState('');
  const [passwordIsValid, setPasswordIsValid] = useState();
  const [formIsValid, setFormIsValid] = useState(false);

  useEffect(()=>{
   const identifier= setTimeout(()=>{
    console.log('triggered only once for all the  keystrokes typed in between 1000millis')
    setFormIsValid(
      enteredEmail.includes('@') && enteredPassword.trim().length > 6
    );
   },1000);
   return ()=>{
    console.log("cleanup...")
    clearTimeout(identifier);
  };  //cleaning up after 5seconds
  },[enteredEmail, enteredPassword])
  const emailChangeHandler = (event) => {
    setEnteredEmail(event.target.value);

    // setFormIsValid( // moved to useEffect.
    //   event.target.value.includes('@') && enteredPassword.trim().length > 6
    // );
  };
const passwordChangeHandler = (event) => {
    setEnteredPassword(event.target.value);

    setFormIsValid(
      event.target.value.trim().length > 6 && enteredEmail.includes('@')
    );
  };
 const validateEmailHandler = () => {
    setEmailIsValid(enteredEmail.includes('@'));
  };

  const validatePasswordHandler = () => {
    setPasswordIsValid(enteredPassword.trim().length > 6);
  };

  const submitHandler = (event) => {
    event.preventDefault();
    props.onLogin(enteredEmail, enteredPassword);
  };




  <form onSubmit={submitHandler}>
        <div
          className={`${classes.control} ${
            emailIsValid === false ? classes.invalid : ''
          }`}
        >
          <label htmlFor="email">E-Mail</label>
          <input
            type="email"
            id="email"
            value={enteredEmail} placeholder="UseEffect Used Here-- [Check Console]"
            onChange={emailChangeHandler}
            onBlur={validateEmailHandler}
          />
        </div>
        <div
          className={`${classes.control} ${
            passwordIsValid === false ? classes.invalid : ''
          }`}
        >


FILE: LOGIN.js
import React, { useEffect, useState } from 'react';

import Card from '../UI/Card/Card';
import classes from './Login.module.css';
import Button from '../UI/Button/Button';

const Login = (props) => {
  const [enteredEmail, setEnteredEmail] = useState('');
  const [emailIsValid, setEmailIsValid] = useState();
  const [enteredPassword, setEnteredPassword] = useState('');
  const [passwordIsValid, setPasswordIsValid] = useState();
  const [formIsValid, setFormIsValid] = useState(false);

  useEffect(()=>{
   const identifier= setTimeout(()=>{
    console.log('triggered only once for all the  keystrokes typed in between 1000millis')
    setFormIsValid(
      enteredEmail.includes('@') && enteredPassword.trim().length > 6
    );
   },1000);
   return ()=>{
    console.log("cleanup...")
    clearTimeout(identifier);
  };  //cleaning up after 5seconds
  },[enteredEmail, enteredPassword])
  const emailChangeHandler = (event) => {
    setEnteredEmail(event.target.value);

    // setFormIsValid( // moved to useEffect.
    //   event.target.value.includes('@') && enteredPassword.trim().length > 6
    // );
  };

  const passwordChangeHandler = (event) => {
    setEnteredPassword(event.target.value);

    setFormIsValid(
      event.target.value.trim().length > 6 && enteredEmail.includes('@')
    );
  };

  const validateEmailHandler = () => {
    setEmailIsValid(enteredEmail.includes('@'));
  };

  const validatePasswordHandler = () => {
    setPasswordIsValid(enteredPassword.trim().length > 6);
  };

  const submitHandler = (event) => {
    event.preventDefault();
    props.onLogin(enteredEmail, enteredPassword);
  };

  return (
    <Card className={classes.login}>
      <form onSubmit={submitHandler}>
        <div
          className={`${classes.control} ${
            emailIsValid === false ? classes.invalid : ''
          }`}
        >
          <label htmlFor="email">E-Mail</label>
          <input
            type="email"
            id="email"
            value={enteredEmail} placeholder="UseEffect Used Here-- [Check Console]"
            onChange={emailChangeHandler}
            onBlur={validateEmailHandler}
          />
        </div>
        <div
          className={`${classes.control} ${
            passwordIsValid === false ? classes.invalid : ''
          }`}
        >
          <label htmlFor="password">Password</label>
          <input
            type="password"
            id="password"
            value={enteredPassword}
            onChange={passwordChangeHandler}
            onBlur={validatePasswordHandler}
          />
        </div>
        <div className={classes.actions}>
          <Button type="submit" className={classes.btn} disabled={!formIsValid}>
            Login
          </Button>
        </div>
      </form>
    </Card>
  );
};

export default Login;

Wednesday, November 30, 2022

usereducer

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


const emailReducer = (state, action) => {
  if (action.type === "USER_INPUT") {
    return { value: action.val, isValid: action.val.length > 5 ? true : false };
  }
  if (action.type === "INPUT_BLUR") {
    return {
      value: state.value,
      isValid: state.value.length > 5 ? true : false,
    };
  }
  return { value: "", isValid: false };
};

const passwordReducer = (state, action) => {
  if (action.type === "PASS_IP") {
    return {
      value: action.value,
      isValid: action.value.length > 5 ? true : false,
    };
  } else if (action.type === "PASS_BLUR") {
    return {
      value: state.value,
      isValid: state.value.length > 5 ? true : false,
    };
  } else {
    return { value: "", isValid: null };
  }
};
const Login = () => {
  const [formIsValid, setFormIsValid] = useState(false);
  const [emailState, dispatchEmail] = useReducer(emailReducer, {
    value: "",
    isValid: null,
  });
  const [passState, dispatchpass] = useReducer(passwordReducer, {
    value: "",
    isValid: null,
  });

  //---------

  useEffect(() => {
    console.log("EFFECT RUNNING");

    return () => {
      console.log("EFFECT CLEANUP");
    };
  }, []);
  const { isValid: emailIsValid } = emailState;
  const { isValid: passwordIsValid } = passState;

  useEffect(() => {
    const identifier = setTimeout(() => {
      console.log("Checking form validity!");
      setFormIsValid(emailIsValid && passwordIsValid);
    }, 500);

    return () => {
      console.log("CLEANUP");
      clearTimeout(identifier);
    };
  }, [emailIsValid, passwordIsValid]);
  //---------------

  const emailChangeHandler = (event) => {
    dispatchEmail({ type: "USER_INPUT", val: event.target.value });
    console.log("dis em");
  };

  const validateEmailHandler = () => {
    dispatchEmail({ type: "INPUT_BLUR" });
  };

  const passwordHandler = (event) => {
    dispatchpass({ type: "PASS_IP", value: event.target.value });
  };
  const passwordBlurHandler = () => {
    dispatchpass({ type: "PASS_BLUR" });
  };
  const submitHandler = (event) => {
    event.preventDefault();
    // props.onLogin(emailState.value, enteredPassword);
  };

  return (
    <form onSubmit={submitHandler}>
      email:{emailState.isValid}
      pass:{passState.isValid}
      <div>
        {emailState.value}
        <label htmlFor="email">E-Mail</label>
        <input
          style={{ color: emailState.isValid ? "" : "red" }}
          type="email"
          id="email"
          value={emailState.value}
          onChange={emailChangeHandler}
          onBlur={validateEmailHandler}
        />
      </div>
      <input
        type="password"
        value={passState.value}
        onChange={passwordHandler}
        onBlur={passwordBlurHandler}
      />
      <button type="submit" disabled={!formIsValid}>
        submit
      </button>
    </form>
  );
};
export default Login;

Tuesday, November 29, 2022

React: usereducer

 LOGIN.js


Globally


const emailReducer = (state, action) => {

  if (action.type === 'USER_INPUT') {

    return { value: action.val, isValid: action.val.includes('@')};

  }

  if (action.type === 'INPUT_BLUR') {

    return { value: state.value, isValid: state.value.includes('@') };

  }

  return { value: '', isValid: false };

};


Inside Login Function

const [emailState, dispatchEmail] = useReducer(emailReducer, {

    value: '',

    isValid: null,

  });



const emailChangeHandler = (event) => {

    dispatchEmail({type: 'USER_INPUT', val: event.target.value});


    setFormIsValid(

      event.target.value.includes('@') && enteredPassword.trim().length > 6

    );

  };

  

    const validateEmailHandler = () => {

    dispatchEmail({type: 'INPUT_BLUR'});

  };

  

  

  

  const submitHandler = (event) => {

    event.preventDefault();

    props.onLogin(emailState.value, enteredPassword);

  };

  

  

  

  

  return (

    <Card className={classes.login}>

      <form onSubmit={submitHandler}>

        <div

          className={`${classes.control} ${

            emailState.isValid === false ? classes.invalid : ''

          }`}

        >

          <label htmlFor="email">E-Mail</label>

          <input

            type="email"

            id="email"

            value={emailState.value}

            onChange={emailChangeHandler}

            onBlur={validateEmailHandler}

          />

        </div>

Monday, November 21, 2022

IMP: Debouncing : useEffect

 


useEffect(()=>{
const identifier=setTimeout(()=>{
setFormIsValid(
enteredEmail.includes('@') && enteredPassword.trim().length>6
)
},500)
return ()=>{
console.log('Cleanup');
clearTimeout(identifier);
}
},[enteredEmail,enteredPassword])


Thursday, November 17, 2022

React: Popup modal

Add backdrop to root for click
app.js

import logo from './logo.svg';
import './App.css';
import Modal from './modal/Modal';
import { useState } from 'react';

function App() {
  const [showPop,setShowPop]=useState(false)
  const subForm=()=>{
    setShowPop(true)
  }
  return (
    <div className="App">
     <button onClick={subForm}>show</button>
    {showPop && <Modal></Modal>}
    </div>
  );
}

export default App;
-----------------------------------------------------------
Modal.js
import React, { Fragment } from "react";
import classes from './Modal.module.css';

const Modal=()=>{
return <Fragment><div className={classes.backdrop}><div className={classes.modal}>
<header className={classes.header}>
    <h2>Error</h2>
</header>
<div className={classes.content}>this is body</div>
<footer className={classes.actions}>
    okay
</footer>
</div></div></Fragment>
}
export default Modal;
----------------------------------------------------------
.backdrop {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100vh;
    z-index: 10;
    background: rgba(0, 0, 0, 0.75);
  }

.modal {
    position:fixed;
    top:30vh;
    left:10%;
    width: 80%;
    overflow: hidden;
    z-index: 100;
      }
     
.header{
background-color: gray;
padding: 1rem;
}

.header h2{
    margin: 0;
    color: white;
    }

.content{
padding: 1rem;
background-color: white;
}

.actions{
padding: 1rem;
display: flex;
justify-content: flex-end;
background-color: gray;
}


@media (min-width: 768px) {// used for adjusting size
    .modal {
      left: calc(50% - 20rem);
      width: 40rem;
    }
  }