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};
  }
}