CaloriesInput.tsx 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import React, { FormEvent } from 'react';
  2. import { IconButton } from '../button/IconButton';
  3. import styles from './caloriesInput.css';
  4. type CaloriesInputProps = {
  5. addCalories: (calories: { title: string, count: number}) => void,
  6. saveCalories: (calories: { title: string, count: number}) => void,
  7. item?: CalorieValue
  8. };
  9. interface ICalorieInputForm extends HTMLFormElement {
  10. caloriesTitle: HTMLInputElement;
  11. caloriesCount: HTMLInputElement;
  12. }
  13. function CaloriesInput ({ addCalories, saveCalories, item }: CaloriesInputProps) {
  14. function onSubmit (event: FormEvent<ICalorieInputForm>) {
  15. event.preventDefault();
  16. const form = event.currentTarget;
  17. const title = form.caloriesTitle.value;
  18. const count = Number(form.caloriesCount.value) || 0;
  19. if (!item) {
  20. addCalories({ title, count });
  21. form.querySelectorAll('input').forEach((formElement) => {
  22. formElement.value = '';
  23. formElement.blur();
  24. });
  25. } else {
  26. saveCalories({ title, count});
  27. }
  28. }
  29. const {
  30. title: itemTitle = '',
  31. count: itemCount = ''
  32. } = item || {};
  33. const buttonIcon = item
  34. ? 'tick'
  35. : 'plus';
  36. return (
  37. <form onSubmit={onSubmit} className={styles.caloriesInput}>
  38. <div className={styles.inputWrapper}>
  39. <div className={styles.formRow}>
  40. <label htmlFor="caloriesTitle">Nahrungsmittel:</label>
  41. <input id="caloriesTitle" name="caloriesTitle" type="text" defaultValue={itemTitle} required />
  42. </div>
  43. <div className={styles.formRow}>
  44. <label htmlFor="caloriesCount">Kalorien:</label>
  45. <input id="caloriesCount" name="caloriesCount" type="number" defaultValue={itemCount} required />
  46. </div>
  47. </div>
  48. <div className={styles.buttonWrapper}>
  49. <IconButton icon={buttonIcon} buttonClassName={styles.addButton} />
  50. </div>
  51. </form>
  52. );
  53. }
  54. export {
  55. CaloriesInput
  56. };