Created
August 20, 2020 18:08
-
-
Save adarshaacharya/02075246c7c6205f00a8184e30fb40c0 to your computer and use it in GitHub Desktop.
Custom hooks to handle the value change in form inputs.
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 from 'react'; | |
type Props = { | |
title?: string; | |
}; | |
type TReturn = [Props, (event: React.FormEvent<HTMLInputElement>) => void]; | |
const useForm = (initialVal: Props): TReturn => { | |
const [formData, setFormData] = React.useState(initialVal || {}); | |
const handleInput = (event: React.FormEvent<HTMLInputElement>) => { | |
setFormData({ | |
...formData, | |
[event.currentTarget.name]: event.currentTarget.value, | |
}); | |
}; | |
return [formData, handleInput]; | |
}; | |
export default useForm; | |
// Snippet component | |
const initialVal = { title: '' }; | |
const [formData, handleInput] = useForm(initialVal); | |
<form onSubmit={onFormSubmit} autoComplete='off'> | |
<input | |
type='text' | |
name='title' | |
id='title' | |
placeholder='Type snippet title..' | |
value={formData.title} | |
onChange={handleInput} | |
required={true} | |
/> | |
</form> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment