Advertisement
aldikhan13

React Custom Hooks useForm

Jul 2nd, 2020
318
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React, { useState } from "react";
  2.  
  3. // custom hooks useForm
  4. const useForm = callback => {
  5.   const [values, setValues] = useState({});
  6.   return {
  7.     values,
  8.     onChange: e => {
  9.       setValues({
  10.         ...values,
  11.         [e.target.name]: e.target.value
  12.       });
  13.     },
  14.     onSubmit: e => {
  15.       e.preventDefault();
  16.       callback();
  17.     }
  18.   };
  19. };
  20.  
  21. // app component
  22. export default function App() {
  23.   const { values, onChange, onSubmit } = useForm(() => {
  24.     console.log(values.username);
  25.     console.log(values.email);
  26.   });
  27.   return (
  28.     <div>
  29.       <form onSubmit={onSubmit}>
  30.         <input type="text" name="username" onChange={onChange} />
  31.         <input type="email" name="email" onChange={onChange} />
  32.         <input type="submit" value="Sing-in" />
  33.       </form>
  34.     </div>
  35.   );
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement