Input Switch คือ กล่องรับค่า on (เป็นจริง) หรือ off (เป็นเท็จ)
import { useEffect, useState } from "react";
import styled from "styled-components";
export default function InputSwitch({
value,
onChange,
className,
backgroundColor = "#3f3f42",
switchOffColor = "#ccc",
switchOnColor = "#198754",
height = "20px",
width = "40px",
style,
}) {
const [isOn, setIsOn] = useState(false);
useEffect(() => {
if (value) {
setIsOn(value);
}
}, []);
const handleClicked = () => {
const inverseOn = !isOn;
setIsOn(inverseOn);
if (onChange) {
onChange(inverseOn);
}
};
return (
<Styled
className={className}
style={style}
onClick={handleClicked}
$backgroundColor={backgroundColor}
$switchOffColor={switchOffColor}
$switchOnColor={switchOnColor}
$height={height}
$width={width}
>
<div className={"switchButton" + (isOn ? " on" : "")}></div>
<div className={"switchHole" + (isOn ? " hole" : "")}></div>
</Styled>
);
}
const Styled = styled.div`
position: relative;
display: inline-block;
width: ${({ $width }) => $width};
height: ${({ $height }) => $height};
cursor: pointer;
overflow: hidden;
border-radius: ${({ $height }) => $height};
.switchButton {
position: absolute;
width: ${({ $height }) => $height};
height: ${({ $height }) => $height};
background-color: ${({ $backgroundColor }) => $backgroundColor};
border-radius: 100%;
left: 0;
}
.on {
background-color: ${({ $switchOnColor }) => $switchOnColor};
left: auto;
right: 0;
}
.switchHole {
height: ${({ $height }) => $height};
background-color: ${({ $switchOffColor }) => $switchOffColor};
opacity: 0.28;
border-radius: ${({ $height }) => $height};
}
.hole {
background-color: ${({ $switchOnColor }) => $switchOnColor};
}
`;
import { useState } from "react";
import InputSwitch from "../../lib/view/example/InputSwitch";
export default function Test() {
const [isOn, setIsOn] = useState(true);
return (
<div style={{ padding: "200px" }}>
<InputSwitch value={isOn} onChange={(e) => setIsOn(e)} />
</div>
);
}
Property | Description | Type | Default |
---|---|---|---|
value | กำหนดค่า true เมื่อต้องการเปิด switch | boolean | |
onChange | ฟังก์ชันจะทำงานเมื่อทำการเปลี่ยนค่า | function | |
className | ใช้กำหนดลักษณะเฉพาะของ view | string | |
backgroundColor | สีพื้นหลังของ view | string | "#3f3f42" |
switchOffColor | สีสถานะปิดของ switch | string | "#ccc" |
switchOnColor | สีสถานะเปิดของ switch | string | "#198754" |
height | ความสูงของ view | string | "20px" |
width | ความกว้างของ view | string | "40px" |
style | inline style ของ view | CSSProperties |