Skip to content

Instantly share code, notes, and snippets.

@guy-kdm
Created June 13, 2017 09:30
Show Gist options
  • Save guy-kdm/08b607e677c43f4f8008e8aea3589986 to your computer and use it in GitHub Desktop.
Save guy-kdm/08b607e677c43f4f8008e8aea3589986 to your computer and use it in GitHub Desktop.
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