Skip to content

Instantly share code, notes, and snippets.

@intelliapps-io
Created July 9, 2019 21:03
Show Gist options
  • Save intelliapps-io/430c1fef409a4f1ca86d6e80c592d3bb to your computer and use it in GitHub Desktop.
Save intelliapps-io/430c1fef409a4f1ca86d6e80c592d3bb to your computer and use it in GitHub Desktop.
useForm Hook
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