I've imported a Switch/Toggle component from HeadlessUI (https://headlessui.com/react/switch) to my NextJS app but I'm having some trouble passing it's state (true/false) to the parent component.
When I try to replace onChange={setEnabled} or checked={enabled} by anything else, the toggle stops switching. Therefore I can't replace it by props.setEnabled nor by a function because even if I don't get any error, they don't get executed.
Here's a screen recording hosted on Loom demonstrating my issue: https://www.loom.com/share/dac2ffa6060a48729c79c89e1524aca4
Thank you for your help ! Let me know if you need additional info.
import { useState } from "react";
import { Switch } from "@headlessui/react";
function classNames(...classes) {
return classes.filter(Boolean).join(" ");
}
export default function Toggle(props) {
const [enabled, setEnabled] = useState();
// I TRIED TO PASS THIS FUNCTION TO onChange BUT IT DOESN'T WORK
// const handleToggleState = () => {
// function switchToggle(){
// if (enabled == true) {
// setEnabled(false);
// } else {
// setEnabled(true);
// }
// }}
return (
<Switch
checked={enabled}
onChange={setEnabled}
className={classNames(
enabled ? "bg-indigo-600" : "bg-gray-200",
"relative inline-flex flex-shrink-0 h-5 w-11 border-2 border-transparent rounded-full cursor-pointer transition-colors ease-in-out duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
)}
>
<span className="sr-only">Use setting</span>
<span
aria-hidden="true"
className={classNames(
enabled ? "translate-x-5" : "translate-x-0",
"pointer-events-none inline-block h-4 w-4 rounded-full bg-white shadow transform ring-0 transition ease-in-out duration-200"
)}
/>
</Switch>
);
}