View difference between Paste ID: 6F9vKuhp and 1muWcMDY
SHOW: | | - or go back to the newest paste.
1
// pages/cms/products/components/CMSProductForm.tsx
2
import clsx from 'clsx';
3-
import { ChangeEvent, FormEvent, useState } from 'react';
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
}
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
  useEffect(() => {
19
    if (props.activeItem) {
20
      setFormData({ ...props.activeItem })
21
    }
22
  }, [props.activeItem])
23
24
  function changeHandler(e: ChangeEvent<HTMLInputElement>) {
25
    const name = e.currentTarget.value;
26
    setFormData(s => ({ ...s, name }))
27
  }
28
29
  function saveHandler(e: FormEvent<HTMLFormElement>) {
30
    e.preventDefault();
31
    console.log(formData)
32
  }
33
34
  const isNameValid = formData.name?.length;
35
  const isValid = isNameValid;
36
37
  return (
38
    <div className={clsx(
39
      'fixed bg-slate-200 z-10 text-black top-0 w-96  h-full transition-all',
40
      {'-right-96': !props.activeItem, 'right-0': props.activeItem}
41
    )}>
42
43
      <form onSubmit={saveHandler}>
44
        <div className="flex justify-around h-16">
45
          <button
46
            className="text-white w-1/2 bg-green-500 hover:bg-green-600 disabled:opacity-30"
47
            disabled={!isValid}
48
            type="submit"
49
          >SAVE</button>
50
          <button
51
            className="text-white w-1/2 bg-slate-500 hover:bg-slate-600"
52
            onClick={props.onClose}
53
            type="button"
54
          >CLOSE</button>
55
        </div>
56
57
        <div className="flex flex-col gap-3 mx-3 mt-16">
58
          Product Name:
59
          <input
60
            className={clsx({ 'error': !isNameValid})}
61
            type="text" value={formData?.name} onChange={changeHandler}
62
          />
63
        </div>
64
      </form>
65
66
      {props.activeItem?.name}
67
68
    </div>
69
  )
70
}
71