@nafr/echo-ui
Version:
A UI library born for WAA
29 lines (28 loc) • 1.66 kB
JavaScript
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { forwardRef, useEffect, useState } from 'react';
import { cn } from '../../../lib/utils';
import { SIZE } from './constants';
import { useStyle } from './styles';
export const Switch = forwardRef((props, ref) => {
const { toggled: _toggled = false, disabled = false, size = SIZE, classNames, styles, onClick, onChange, ...restProps } = props;
const [toggled, setToggled] = useState(_toggled); // useState to track the toggled state
// useEffect to call onChange prop whenever toggled state changes
useEffect(() => {
if (disabled)
return;
onChange?.(toggled);
}, [toggled, disabled, onChange]);
// Sync the component's toggled state with the toggled prop
useEffect(() => {
setToggled(_toggled);
}, [_toggled]);
// Handle click event
const handleClick = (e) => {
if (disabled)
return;
setToggled(!toggled);
onClick && onClick(e);
};
const { base, button, thumb, label } = useStyle({ disabled, toggled, size });
return (_jsxs("label", { ...restProps, ref: ref, "data-toggled": toggled, "data-disabled": disabled, className: cn(base(), restProps.className), style: restProps.style, onClick: handleClick, children: [_jsx("span", { className: cn(button(), classNames?.button), style: styles?.button, children: _jsx("span", { className: cn(thumb(), classNames?.thumb), style: { ...styles?.thumb, left: toggled ? `calc(50% + 0.75rem / 2)` : '' } }) }), _jsx("span", { className: cn(label(), classNames?.label), style: styles?.label, children: restProps.children })] }));
});