Skip to content

Instantly share code, notes, and snippets.

@adarshaacharya
Created August 20, 2020 18:08
Show Gist options
  • Save adarshaacharya/02075246c7c6205f00a8184e30fb40c0 to your computer and use it in GitHub Desktop.
Save adarshaacharya/02075246c7c6205f00a8184e30fb40c0 to your computer and use it in GitHub Desktop.
Custom hooks to handle the value change in form inputs.
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