Apologies in advanced, I am really struggling with React-hook-forms, any help is much appreciated.
I've managed to get my form fields prepopulated from a database, but my problem arises when trying to use custom inputs.
I have a Checkbox component like so:
import React from "react";
const Checkbox = React.forwardRef(
(
{
label,
name,
value,
onChange,
defaultChecked,
onBlur,
type,
...rest
}: any,
forwardedRef: any
) => {
const [checked, setChecked] = React.useState(defaultChecked);
React.useEffect(() => {
if (onChange) {
onChange(checked);
}
}, []);
React.useEffect(() => {
}, [checked]);
return (
<div onClick={() => setChecked(!checked)} style={{ cursor: "pointer" }}>
<label htmlFor={name}>{label}</label>
<input
type="checkbox"
value={value}
name={name}
onBlur={onBlur}
ref={forwardedRef}
checked={checked}
{...rest}
/>
[{checked ? "X" : " "}]{label}
</div>
);
}
);
export default Checkbox;
Which gets default values and applies them to the component:
import "./styles.css";
import Checkbox from "./Checkbox";
import { useForm } from "react-hook-form";
const defaultValues = {
gender: "male"
};
export default function App() {
const { handleSubmit, register } = useForm({
defaultValues: defaultValues
});
const onSubmit = async (data: any) => {
console.log(data, "data");
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<Checkbox
{...register("gender")}
name={"gender"}
value={"boy"}
label={"Boy"}
// when this added, the custom checks work but everything is checked
// defaultChecked={defaultValues}
/>
</form>
);
}
But when I call the onChange function I get the following error:
Cannot read properties of undefined (reading 'target')
The behavior is working as expected when just clicking on the checkboxes, and the default state is loaded for the native inputs, but it doesn't reflect the custom checkbox UI without user interaction.
Here's a codesandbox showing my issue.
What am I doing wrong