Created
June 13, 2017 09:30
-
-
Save guy-kdm/08b607e677c43f4f8008e8aea3589986 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
function getAllInputs(target) { | |
const domData = new FormData(target); | |
const data = {}; | |
[...domData.keys()].forEach(key => data[key] = domData.get(key)); | |
return data; | |
} | |
function getSingleInput(target) { | |
const domData = new FormData(target); | |
return domData.get([...domData.keys()][0]); | |
} | |
// todo: warn if no formdata (did you forget to name your inputs?) | |
function SubmitableForm({ onSubmit, children, submitOnChange, singleInput }) { | |
if (typeof onSubmit !== "function") | |
console.error( | |
`SubmitableForm expected an onSubmit function but recieved ${typeof onSubmit}.`, | |
{ onSubmit } | |
); | |
const getData = singleInput ? getSingleInput : getAllInputs; | |
const handleSubmit = target => onSubmit(getData(target)); | |
return ( | |
<form | |
onSubmit={e => { | |
e.preventDefault(); | |
handleSubmit(e.target); | |
}} | |
onChange={submitOnChange && (e => handleSubmit(e.target.form))} | |
noValidate | |
> | |
{children} | |
</form> | |
); | |
} | |
export default SubmitableForm; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment