Skip to content

Instantly share code, notes, and snippets.

@mulrooneydesign
Last active November 14, 2023 19:46
Show Gist options
  • Save mulrooneydesign/c656f4cfb2cf1ee971c2e6b82652af98 to your computer and use it in GitHub Desktop.
Save mulrooneydesign/c656f4cfb2cf1ee971c2e6b82652af98 to your computer and use it in GitHub Desktop.
My example of how to build my own react useForm hook
import { useState } from "react";
function useForm({ initialValue, name }) {
const [value, setValue] = useState(initialValue);
return {
[`${name}`]: {
value,
onChange: (e) => setValue(e.target.value)
}
};
}
export function Form() {
const { firstName } = useForm({
initialValue: "",
name: "firstName"
});
const { lastName } = useForm({
initialValue: "",
name: "lastName"
});
return (
<FormWrapper>
<Input value={firstName.value} onChange={firstName.onChange} />
<Input value={lastName.value} onChange={lastName.onChange} />
</FormWrapper>
);
}
function Input(props) {
const { value } = props;
return (
<>
<label htmlFor="first">First Name {value}</label>
<input id="first" type="text" {...props} />
</>
);
}
function FormWrapper({ children }) {
return <form>{children}</form>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment