Advertisement
fabiobiondi

React Pro - Real World App - Ch9. 09. Product Form - Controlled Form e Validazioni

Mar 23rd, 2023
1,142
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, useState } from 'react';
  4. import { Product } from '@/model/product';
  5.  
  6. export interface CMSProductFormProps {
  7.   activeItem: Partial<Product> | null;
  8.   onClose: () => void;
  9. }
  10.  
  11. const initialState: Partial<Product> = {
  12.   name: '', cost: 0, description: ''
  13. }
  14.  
  15. export function CMSProductForm(props: CMSProductFormProps) {
  16.   const [formData, setFormData] = useState(initialState);
  17.  
  18.   function changeHandler(e: ChangeEvent<HTMLInputElement>) {
  19.     const name = e.currentTarget.value;
  20.     setFormData(s => ({ ...s, name }))
  21.   }
  22.  
  23.   function saveHandler(e: FormEvent<HTMLFormElement>) {
  24.     e.preventDefault();
  25.     console.log(formData)
  26.   }
  27.  
  28.   const isNameValid = formData.name?.length;
  29.   const isValid = isNameValid;
  30.  
  31.   return (
  32.     <div className={clsx(
  33.       'fixed bg-slate-200 z-10 text-black top-0 w-96  h-full transition-all',
  34.       {'-right-96': !props.activeItem, 'right-0': props.activeItem}
  35.     )}>
  36.  
  37.       <form onSubmit={saveHandler}>
  38.         <div className="flex justify-around h-16">
  39.           <button
  40.             className="text-white w-1/2 bg-green-500 hover:bg-green-600 disabled:opacity-30"
  41.             disabled={!isValid}
  42.             type="submit"
  43.           >SAVE</button>
  44.           <button
  45.             className="text-white w-1/2 bg-slate-500 hover:bg-slate-600"
  46.             onClick={props.onClose}
  47.             type="button"
  48.           >CLOSE</button>
  49.         </div>
  50.  
  51.         <div className="flex flex-col gap-3 mx-3 mt-16">
  52.           Product Name:
  53.           <input
  54.             className={clsx({ 'error': !isNameValid})}
  55.             type="text" value={formData?.name} onChange={changeHandler}
  56.           />
  57.         </div>
  58.       </form>
  59.  
  60.       {props.activeItem?.name}
  61.  
  62.     </div>
  63.   )
  64. }
  65.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement