AddProductForm.tsx 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import React, { useState } from 'react';
  2. import { Product } from '../types';
  3. interface AddProductFormProps {
  4. onAddProduct: (product: Product) => void;
  5. }
  6. const AddProductForm: React.FC<AddProductFormProps> = ({ onAddProduct }) => {
  7. const [name, setName] = useState('');
  8. const [price, setPrice] = useState('');
  9. const handleSubmit = (e: React.FormEvent) => {
  10. e.preventDefault();
  11. if (name && price) {
  12. onAddProduct({ name, price: parseFloat(price), id: 0 });
  13. setName('');
  14. setPrice('');
  15. }
  16. };
  17. return (
  18. <form onSubmit={handleSubmit}>
  19. <h2>Add New Product</h2>
  20. <div>
  21. <label htmlFor="name">Name:</label>
  22. <input
  23. type="text"
  24. id="name"
  25. value={name}
  26. onChange={(e) => setName(e.target.value)}
  27. required
  28. />
  29. </div>
  30. <div>
  31. <label htmlFor="price">Price:</label>
  32. <input
  33. type="number"
  34. id="price"
  35. value={price}
  36. onChange={(e) => setPrice(e.target.value)}
  37. min="0"
  38. step="0.01"
  39. required
  40. />
  41. </div>
  42. <button type="submit">Add Product</button>
  43. </form>
  44. );
  45. };
  46. export default AddProductForm;