Skip to content

Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.

806 B
Raw Blame
import {
  type ForwardRefExoticComponent,
  type ComponentProps,
  type RefAttributes,
  forwardRef,
  useEffect,
  useState,
} from "react";
import { Root, Thumb } from "@radix-ui/react-switch";

export const Switch = forwardRef<
  HTMLButtonElement,
  ComponentProps<typeof Root>
>(({ defaultChecked, ...props }, ref) => {
  const currentChecked = props.checked ?? defaultChecked ?? false;
  const [checked, setChecked] = useState(currentChecked);
  // synchronize external value with local one when changed
  useEffect(() => setChecked(currentChecked), [currentChecked]);
  return (
    <Root {...props} ref={ref} checked={checked} onCheckedChange={setChecked} />
  );
});

export const SwitchThumb: ForwardRefExoticComponent<
  ComponentProps<typeof Thumb> & RefAttributes<HTMLSpanElement>
> = Thumb;