Guest User

Untitled

a guest
Nov 17th, 2018
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 KB | None | 0 0
  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. }
Add Comment
Please, Sign In to add comment