Skip to main content

Switch

Switch.tsx
import React, { useState, useCallback } from 'react';
import styles from './Switch.module.css';

type SwitchProps = {
label: string;
value: boolean;
onChange: (value: boolean) => void;
}

const Switch = (props: SwitchProps) => {
const { label, value, onChange } = props;
const [isChecked, setIsChecked] = useState<boolean>(value);

const handleToggle = useCallback(() => {
setIsChecked(prevChecked => !prevChecked);
onChange(!isChecked);
}, [isChecked, onChange]);

return (
<div className={styles.switch}>
<label>
{label}
<input type="checkbox" checked={isChecked} onChange={handleToggle} />
<span className={styles.slider} />
</label>
</div>
);
};

export default Switch;


Switch.module.css
.switch {
display: flex;
align-items: center;
margin: 8px;
}

.switch label {
display: flex;
align-items: center;
font-size: 14px;
cursor: pointer;
}

.switch input[type="checkbox"] {
display: none;
}

.switch .slider {
position: relative;
display: inline-block;
width: 40px;
height: 20px;
margin-left: 8px;
border-radius: 34px;
background-color: #ccc;
transition: background-color 0.3s;
}

.switch .slider:before {
position: absolute;
content: "";
width: 16px;
height: 16px;
border-radius: 50%;
background-color: #fff;
top: 2px;
left: 2px;
transition: transform 0.3s;
}

.switch input[type="checkbox"]:checked + .slider {
background-color: #2196f3;
}

.switch input[type="checkbox"]:checked + .slider:before {
transform: translateX(20px);
}