I created a helper function to reduce some functions in components. So whenever I need that helper function I could use them in the component needed. I don't know what is the correct way of doing it but I tried this way. I need to pass form, setForm state and event to the helper function. For example.
Main.js
import { useState } from "react";
// helper
import HandleChange from "./HandleChange";
function Main() {
const [form, setForm] = useState({
firstName: "",
lastName: "",
});
// ------> This is what I want to move to helper component.
// function handleChange(event) {
// const { name, value } = event.target;
// setForm({
// ...form,
// [name]: value,
// });
// }
// ------> This is how I used helper component
const handleChange = HandleChange(form, setForm, event);
return (
<input
type="text"
name="firstName"
value={form.firstName}
{/****** this is how I passed handleChange ******/}
onChange={handleChange}
/>
)
}
Helper.js
export default function HandleChange(form, setForm, event) {
const { name, value } = event.target;
setForm({
...form,
[name]: value,
});
}