Advertisement
fabiobiondi

React Pro - Real World App - Ch6. 14 Form Prevent Default

Mar 18th, 2023 (edited)
1,015
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // pages/checkout/CheckoutPage.tsx
  2.  
  3. import clsx from 'clsx';
  4. import { selectTotalCartCost, useCart } from '@/services/cart';
  5. import { ChangeEvent, useState } from 'react';
  6.  
  7. export const EMAIL_REGEX = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  8.  
  9. export function CheckoutPage() {
  10.   const [user, setUser] = useState({ name: '', email: ''});
  11.   const [dirty, setDirty] = useState(false);
  12.  
  13.   const totalCartCost = useCart(selectTotalCartCost);
  14.  
  15.   function changeHandler(e: ChangeEvent<HTMLInputElement>) {
  16.     const name = e.currentTarget.name;
  17.     const value = e.currentTarget.value;
  18.     setUser(state => ({ ...state, [name]: value }));
  19.     setDirty(true);
  20.   }
  21.  
  22.  
  23.   function sendOrder(e: React.FormEvent<HTMLFormElement>) {
  24.     e.preventDefault()
  25.     console.log(user)
  26.   }
  27.  
  28.  
  29.   const isNameValid = user.name.length;
  30.   const isEmailValid = user.email.match(EMAIL_REGEX);
  31.   const isValid = isNameValid && isEmailValid;
  32.  
  33.   return (
  34.     <div className="max-w-sm mx-auto">
  35.       <h1 className="title">CHECKOUT</h1>
  36.  
  37.       <div className="text-xl my-3 border-b">{totalCartCost}</div>
  38.  
  39.       <form className="flex flex-col gap-3" onSubmit={sendOrder}>
  40.         Your name:
  41.         <input
  42.           type="text" placeholder="your name"
  43.           name="name"
  44.           value={user.name}
  45.           onChange={changeHandler}
  46.           className={clsx({ 'error': !isNameValid && dirty})}
  47.         />
  48.  
  49.         Your email
  50.         <input
  51.           type="email" placeholder="Your email"
  52.           name="email"
  53.           value={user.email}
  54.           onChange={changeHandler}
  55.           className={clsx({ 'error': !isEmailValid && dirty })}
  56.         />
  57.  
  58.         <button type="submit" className="btn primary" disabled={!isValid}>
  59.           CONFIRM ORDER
  60.         </button>
  61.       </form>
  62.  
  63.       <pre>{JSON.stringify(user, null, 2)}</pre>
  64.     </div>
  65.   )
  66. }
  67.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement