Custom Hook for Form Handling in React
Table of contents
Implementation
This hook will manage form inputs and validation, providing an easy way to track form states and perform validation on inputs.
import { useState } from 'react';
function useForm(inputs) {
const [formValues, setFormValues] = useState(inputs);
const handleChange = (event) => {
const { name, value } = event.target;
setFormValues({ ...formValues, [name]: value });
};
const handleSubmit = (callback) => (event) => {
event.preventDefault();
callback();
};
// Add validation logic here if needed
return {
handleChange,
handleSubmit,
values: formValues,
};
}
Usage in Components
To use this hook in your React components, you would import them and call them within the components, providing the necessary arguments (like initial form values for useForm
). This hook abstracts away the complex logic of data fetching and form handling, making your components cleaner and more focused on the presentation logic.
import React from 'react';
import useForm from './useForm'; // Path to the useForm hook
function MyFormComponent() {
const inputs = { name: '', email: '' }; // Initial form values
const { handleChange, handleSubmit, values } = useForm(inputs);
const submitHandler = (event) => {
console.log(values); // Logs the current form values
// Handle form submission...
};
return (
<form onSubmit={handleSubmit(submitHandler)}>
<label>
Name:
<input type="text" name="name" onChange={handleChange} value={values.name} />
</label>
<label>
Email:
<input type="email" name="email" onChange={handleChange} value={values.email} />
</label>
<button type="submit">Submit</button>
</form>
);
}
Real-World Example
An e-commerce site could use this hook in a checkout form. TheuseForm
hook simplifies handling user input, validating form data, and submitting the form.