daily pastebin goal
14%
SHARE
TWEET

Untitled

a guest Nov 17th, 2018 78 Never
Upgrade to PRO!
ENDING IN00days00hours00mins00secs
 
  1. import React, { useState } from "react";
  2.  
  3. function byInitialVal(a, c) {
  4.   a[c.props.id] = c.props.defaultValue || "";
  5.   return a;
  6. }
  7.  
  8. export default function Form({ name, children, onSubmit }) {
  9.   const childArray = React.Children.toArray(children);
  10.   const initialState = childArray.reduce(byInitialVal, {});
  11.   const [values, setValue] = useState(initialState);
  12.  
  13.   function createFormField(child) {
  14.     return (
  15.       <div>
  16.         <label htmlFor={child.props.id}>
  17.           <span style={{ textTransform: "capitalize" }}>{child.props.id}</span>
  18.           <child.type
  19.             type={child.props.type}
  20.             id={child.props.id}
  21.             value={values[child.props.id]}
  22.             onChange={({ target }) =>
  23.               setValue({
  24.                 ...values,
  25.                 [child.props.id]: target.value
  26.               })
  27.             }
  28.           />
  29.         </label>
  30.       </div>
  31.     );
  32.   }
  33.  
  34.   return (
  35.     <form
  36.       onSubmit={e => {
  37.         e.preventDefault();
  38.         onSubmit(values);
  39.       }}
  40.       onReset={() => setValue(initialState)}
  41.     >
  42.       {React.Children.map(children, createFormField)}
  43.       <hr/>
  44.       <input type="reset" value="Reset" />
  45.       {' '}
  46.       <input type="submit" value="Submit" />
  47.     </form>
  48.   );
  49. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top