Created
December 23, 2020 14:45
-
-
Save DarkoTrpevski/bcf31dfa5d6aa545b7250ceff25520ec to your computer and use it in GitHub Desktop.
React useForm hook v2
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, { useState, FormEvent, ChangeEvent } from 'react' | |
export interface IUseFormOptions { | |
initialState?: { [key: string]: any } | |
onSuccessSubmit: (inputs: { [key: string]: any }) => void | |
} | |
const useForm = (opts: IUseFormOptions) => { | |
const [ inputs, setInputs ] = useState(opts.initialState || {}) | |
const dispatchInputs = (values: any) => { | |
const newInputs = { ...inputs, ...values } | |
setInputs(newInputs) | |
} | |
const onSubmit = (event: FormEvent<HTMLFormElement>) => { | |
event.preventDefault() | |
opts.onSuccessSubmit(inputs) | |
} | |
const onChange = (event: ChangeEvent<HTMLTextAreaElement | HTMLInputElement>) => { | |
dispatchInputs({ [event.target.name]: event.target.value }) | |
} | |
return { | |
dispatchInputs, | |
inputs, | |
onSubmit, | |
onChange | |
} | |
} | |
export default useForm; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment