I wish to use RadixUi Switch component and that it would work within a form that uses react-hook-form.
I tried to declare a variable "active" in parent component with register function. Then I send this variable as props to a intermediary component which will render RadixUI component. In this intermediary component I tried to pass "active" properties onto Switch.Root. Result is that when I toggle the switch, it's value is not changing.
How can I fix it?
This is parent component code:
const FormOne = (): JSX.Element => {
const {
register,
handleSubmit,
formState: { errors },
} = useForm();
const active = register("active");
const onSubmit = async (data: FieldValues) => {
console.log(data);
};
return (
<form
className={styles["form-one"]}
onSubmit={handleSubmit(onSubmit)}
>
<MySwitch formRegistration={active} />
<button>
<BsCheckSquareFill className='profile-icon' />
</button>
</form>
);
};
This is Intermediary component code
import React from "react";
import styles from "./MySwitch.module.scss";
import * as Switch from "@radix-ui/react-switch";
import { UseFormRegisterReturn } from "react-hook-form";
interface SwitchProps {
formRegistration: UseFormRegisterReturn;
}
const MySwitch = ({ formRegistration }: SwitchProps): JSX.Element => {
return (
<div className='flex-align-center space-between'>
<Switch.Root className={styles["SwitchRoot"]} {...formRegistration}>
<Switch.Thumb className={styles["SwitchThumb"]} />
</Switch.Root>
</div>
);
};
export default MySwitch;