Input Check box คือ view ที่ใช้รับค่าสถานะ เมื่อกด check จะได้ค่า true
import { useEffect, useState } from "react";
import styled from "styled-components";
export default function InputCheckBox({
initValue,
disabled,
onChange,
className,
children,
style,
checkedColor = "#0172ff",
}) {
const [isCheck, setIsCheck] = useState(false);
useEffect(() => {
if (initValue) {
setIsCheck(initValue);
}
}, [initValue]);
const onValueChange = (event) => {
if (!disabled) {
setIsCheck(!isCheck);
if (onChange) {
onChange(event);
}
}
};
return (
<Styled className={className} style={style} $checkedColor={checkedColor}>
<div className={"item"}>
<label className={"label"}>
<input
type="checkbox"
onChange={onValueChange}
checked={isCheck}
className={"check_box"}
disabled={disabled ? true : false}
/>
<span
className={"check_mark" + (disabled ? " check_box_disable" : "")}
></span>
<div className="item-data">{children}</div>
</label>
</div>
</Styled>
);
}
const Styled = styled.div`
position: relative;
.item {
display: block;
position: relative;
}
.check_mark {
position: absolute;
top: 2px;
left: -2px;
height: 20px;
width: 20px;
background-color: #eee;
border-radius: 5px;
background: #fafbfc;
border: 2px solid #dfe1e6;
cursor: pointer;
}
.check_box {
position: absolute;
top: 5px;
}
.check_box:checked ~ .check_mark {
background-color: ${({ $checkedColor }) => $checkedColor};
}
.check_mark:after {
content: "";
position: absolute;
display: none;
cursor: pointer;
}
.check_box:checked ~ .check_mark:after {
display: block;
cursor: pointer;
}
.item .check_mark:after {
left: 5px;
top: 0px;
width: 4px;
height: 10px;
border: solid white;
cursor: pointer;
border-width: 0 2px 2px 0;
transform: rotate(45deg);
}
.check_box_disable {
background-color: #ddd !important;
}
.no_label {
min-height: 22px;
min-width: 22px;
margin-left: 0px;
margin-right: 0px;
display: block;
position: absolute;
top: 0;
cursor: pointer;
}
.label {
margin-left: 30px;
cursor: pointer;
display: flex;
position: relative;
}
.item-data {
user-select: none;
margin-left: 30px;
}
`;
import InputCheckBox from "../../example/CheckBox";
export default function TestView() {
return (
<div className="test-view">
<InputCheckBox onChange={(e) => console.log(e)}>
This is checkbox
</InputCheckBox>
</div>
);
}
Property | Description | Type | Default |
---|---|---|---|
initValue | ค่าเริ่มต้นของ view | boolean | |
disabled | ปิดการทำงานของ view | boolean | |
onChange | ฟังก์ชันจะทำงานเมื่อมีการเปลี่ยนค่า | function | |
className | คุณลักษณะเฉพาะของ view | string | |
children | view ลูกของ checkbox | ReactElement | |
style | inline style | CSSProperties | |
checkedColor | สีพื้นหลังเมื่อกดเลือก view | string | "#0172ff" |