Last active
January 14, 2019 16:58
-
-
Save krolow/1b8c8a7142ed3a14abdefba09c7f5700 to your computer and use it in GitHub Desktop.
Simple react form using hooks
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'; | |
import { useRef } from 'react'; | |
export default function AddMemberPage({ addMember }) { | |
const formRef = useRef(); | |
async function handleSave(event) { | |
event.preventDefault(); | |
const data = formRef.current.getData(); | |
await addMember({ variables: {...data} }); | |
alert('Success!'); | |
formRef.current.reset(); | |
} | |
return ( | |
<Form ref={formRef}> | |
<Form.Input name="name" label="Name"/> | |
<Form.Input name="email" type="email" label="Email"/> | |
<button onClick={handleSave}>Save</button> | |
</Form> | |
); | |
} |
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'; | |
import { forwardRef } from 'react'; | |
import { useRef } from 'react'; | |
import { useImperativeMethods } from 'react'; | |
const Form = forwardRef(FormRef); | |
function FormRef({ children }, ref) { | |
const formRef = useRef(); | |
useImperativeMethods(ref, () => ({ | |
getData() { | |
const data = new FormData(formRef.current); | |
return Array.from(data.entries()).reduce((acc, [key, value]) => { | |
acc[key] = value; | |
return acc; | |
}, {}); | |
}, | |
reset() { | |
formRef.current.reset(); | |
} | |
})); | |
return ( | |
<form className="form" ref={formRef}> | |
{children} | |
</form> | |
); | |
} | |
Form.Input = function Input({ type = 'text', label, defaultValue, ...props }) { | |
return ( | |
<div className="input"> | |
<label> | |
{label} | |
</label> | |
<input | |
{...props} | |
type={type} | |
defaultValue={defaultValue}/> | |
</div> | |
); | |
} | |
export default Form; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment