Advertisement
fabiobiondi

React Pro - Real World App - Ch9. 11. Product Form - gestire EDIT e ADD - part. 1

Mar 23rd, 2023 (edited)
1,389
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // pages/cms/products/components/CMSProductForm.tsx
  2. import clsx from 'clsx';
  3. import { ChangeEvent, FormEvent, useEffect, useState } from 'react';
  4. import { Product } from '@/model/product';
  5.  
  6. export interface CMSProductFormProps {
  7.   activeItem: Partial<Product> | null;
  8.   onClose: () => void;
  9.   onAdd: (product: Partial<Product>) => void;
  10.   onEdit: (product: Partial<Product>) => void;
  11. }
  12.  
  13. const initialState: Partial<Product> = {
  14.   name: '', cost: 0, description: ''
  15. }
  16.  
  17. export function CMSProductForm(props: CMSProductFormProps) {
  18.   const [formData, setFormData] = useState(initialState);
  19.  
  20.   useEffect(() => {
  21.     if (props.activeItem?.id) {
  22.       setFormData({ ...props.activeItem })
  23.     } else {
  24.       setFormData(initialState)
  25.     }
  26.   }, [props.activeItem])
  27.  
  28.   function changeHandler(e: ChangeEvent<HTMLInputElement>) {
  29.     const name = e.currentTarget.value;
  30.     setFormData(s => ({ ...s, name }))
  31.   }
  32.  
  33.   function saveHandler(e: FormEvent<HTMLFormElement>) {
  34.     e.preventDefault();
  35.     if (props.activeItem?.id) {
  36.       props.onEdit(formData);
  37.     } else {
  38.       props.onAdd(formData);
  39.     }
  40.   }
  41.  
  42.   const isNameValid = formData.name?.length;
  43.   const isValid = isNameValid;
  44.  
  45.   return (
  46.     <div className={clsx(
  47.       'fixed bg-slate-200 z-10 text-black top-0 w-96  h-full transition-all',
  48.       {'-right-96': !props.activeItem, 'right-0': props.activeItem}
  49.     )}>
  50.  
  51.       <form onSubmit={saveHandler}>
  52.         <div className="flex justify-around h-16">
  53.           <button
  54.             className="text-white w-1/2 bg-green-500 hover:bg-green-600 disabled:opacity-30"
  55.             disabled={!isValid}
  56.             type="submit"
  57.           >SAVE</button>
  58.           <button
  59.             className="text-white w-1/2 bg-slate-500 hover:bg-slate-600"
  60.             onClick={props.onClose}
  61.             type="button"
  62.           >CLOSE</button>
  63.         </div>
  64.  
  65.         <div className="flex flex-col gap-3 mx-3 mt-16">
  66.           Product Name:
  67.           <input
  68.             className={clsx({ 'error': !isNameValid})}
  69.             type="text" value={formData?.name} onChange={changeHandler}
  70.           />
  71.         </div>
  72.       </form>
  73.  
  74.       {props.activeItem?.name}
  75.  
  76.     </div>
  77.   )
  78. }
  79.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement