Created
December 22, 2021 20:47
-
-
Save RenatoLopes771/3e33d84053de2d2f1d281a0ffdb49cfa to your computer and use it in GitHub Desktop.
Forms without libraries and thousands of use states
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
// By Ben Awad | |
import { useState } from "react"; | |
export function useForm(initialValues) { | |
const [values, setValues] = useState(initialValues); | |
return [ | |
values, | |
(e) => { | |
setValues({ | |
...values, | |
[e.target.name]: e.target.value | |
}); | |
} | |
]; | |
} |
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
// Example | |
import React, { useState } from "react"; | |
import { useForm } from "./useForm"; | |
export default function App() { | |
const [values, handleChange] = useForm({ email: "", password: "" }); | |
return ( | |
<div> | |
<input name="email" value={values.email} onChange={handleChange} /> | |
<input | |
type="password" | |
name="password" | |
value={values.password} | |
onChange={handleChange} | |
/> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment