Last active
November 14, 2023 19:46
-
-
Save mulrooneydesign/c656f4cfb2cf1ee971c2e6b82652af98 to your computer and use it in GitHub Desktop.
My example of how to build my own react useForm hook
This file contains hidden or 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 { useState } from "react"; | |
| function useForm({ initialValue, name }) { | |
| const [value, setValue] = useState(initialValue); | |
| return { | |
| [`${name}`]: { | |
| value, | |
| onChange: (e) => setValue(e.target.value) | |
| } | |
| }; | |
| } | |
| export function Form() { | |
| const { firstName } = useForm({ | |
| initialValue: "", | |
| name: "firstName" | |
| }); | |
| const { lastName } = useForm({ | |
| initialValue: "", | |
| name: "lastName" | |
| }); | |
| return ( | |
| <FormWrapper> | |
| <Input value={firstName.value} onChange={firstName.onChange} /> | |
| <Input value={lastName.value} onChange={lastName.onChange} /> | |
| </FormWrapper> | |
| ); | |
| } | |
| function Input(props) { | |
| const { value } = props; | |
| return ( | |
| <> | |
| <label htmlFor="first">First Name {value}</label> | |
| <input id="first" type="text" {...props} /> | |
| </> | |
| ); | |
| } | |
| function FormWrapper({ children }) { | |
| return <form>{children}</form>; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment