fabiobiondi

React / TS: controlled form

Sep 17th, 2020 (edited)
1,206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // controlled form
  2. import React, { useState } from 'react';
  3. import './App.css';
  4. import cn from 'classnames';
  5.  
  6. interface FormDataProps { username: string, email: string, subscribe: string }
  7.  
  8. const INITIAL_FORM: FormDataProps = { username: '', email: '', subscribe: 'none' };
  9.  
  10. function App() {
  11.   const [formData, setFormData] = useState<FormDataProps>(INITIAL_FORM)
  12.   const [dirty, setDirty] = useState<boolean>(false);
  13.  
  14.   function onSubmitHandler(event: React.FormEvent<HTMLFormElement>) {
  15.     event.preventDefault();
  16.     console.log(formData)
  17.     setFormData(INITIAL_FORM)
  18.  
  19.   }
  20.  
  21.   function onChangeHandler(e: React.ChangeEvent<!!|>) {
  22.     setFormData({
  23.       ...formData,
  24.       [e.currentTarget.name]: e.currentTarget.value
  25.     })
  26.     setDirty(true);
  27.   }
  28.  
  29.   const isUsernameValid = formData.username.length > 2
  30.   const isEmailValid = formData.email.length > 2;
  31.   const valid = isUsernameValid && isEmailValid;
  32.  
  33.   return <div className="centered">
  34.     {!valid && dirty && 'form wrong'}
  35.     <form onSubmit={onSubmitHandler}>
  36.       <input
  37.         className={cn(
  38.           'form-control',
  39.           { 'is-invalid': !isUsernameValid && dirty }
  40.         )}
  41.         type="text"
  42.         value={formData.username}
  43.         onChange={onChangeHandler}
  44.         name="username"
  45.       />
  46.       <input
  47.         type="text"
  48.         className={cn(
  49.           'form-control',
  50.           { 'is-invalid': !isEmailValid && dirty }
  51.         )}
  52.         value={formData.email}
  53.         onChange={onChangeHandler}
  54.         name="email"
  55.       />
  56.       <select value={formData.subscribe} onChange={onChangeHandler} name="subscribe">
  57.         <option value="none">Select your choice</option>
  58.         <option value="yes">yes</option>
  59.         <option value="no">no</option>
  60.       </select>
  61.       <button type="submit" disabled={!valid}>save</button>
  62.     </form>
  63.  
  64.  
  65.   </div>
  66. }
  67.  
  68. export default App;
  69.  
  70.  
Add Comment
Please, Sign In to add comment