Created
July 9, 2019 21:03
-
-
Save intelliapps-io/430c1fef409a4f1ca86d6e80c592d3bb to your computer and use it in GitHub Desktop.
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 React, { useState } from 'react'; | |
import './App.css'; | |
export function useForm<FormFields>(initalValues: FormFields): [FormFields, (event: React.ChangeEvent<any>) => void] { | |
const [values, setValues] = useState<FormFields>(initalValues); | |
return [ | |
values, | |
event => { | |
setValues({ | |
...values, | |
[event.target.name]: event.target.value | |
}) | |
} | |
] | |
} | |
type FormFields = { username: string, password: string } | |
const App = () => { | |
const [values, handleChange] = useForm<FormFields>({ username: "", password: "" }) | |
return( | |
<div> | |
<h2>Test Form</h2> | |
<input placeholder="username" name="username" value={values.username} onChange={handleChange}/> | |
<input placeholder="password" name="password" value={values.password} onChange={handleChange}/> | |
</div> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment