Skip to content

Commit 14a93ca

Browse files
committed
added events
1 parent 6e42276 commit 14a93ca

File tree

2 files changed

+26
-6
lines changed

2 files changed

+26
-6
lines changed

src/components/Checkbox/index.stories.tsx

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,3 +31,13 @@ export const LabelDisable = () => (
3131
<Checkbox labelText='Label Disabled' labelDisabled />
3232
</div>
3333
);
34+
35+
export const Events = () => (
36+
<div className='storybook__container'>
37+
<Checkbox labelText='On Click' clicked={() => alert('clicked')} />
38+
<Checkbox
39+
labelText='On Change'
40+
changed={(checked) => alert(`Checkbox is checked: ${checked}`)}
41+
/>
42+
</div>
43+
);

src/components/Checkbox/index.tsx

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import React, { useState } from 'react';
1+
import React, { useState, ReactElement, useEffect } from 'react';
22

33
import classnames from '../../utils/classNames';
44

@@ -14,14 +14,19 @@ export interface IProps {
1414
labelText?: string;
1515
disabled?: boolean;
1616
labelDisabled?: boolean;
17+
changed?: Function;
18+
clicked?: Function;
1719
}
1820

1921
const baseClass = 'vant-checkbox';
2022

2123
// TODO: Round/Square checkbox
24+
// TODO: Checkbox groups
2225

2326
const Checkbox = ({
2427
checked,
28+
changed,
29+
clicked,
2530
name,
2631
activeIcon = 'checked',
2732
checkedColor = '#1989fa',
@@ -32,20 +37,29 @@ const Checkbox = ({
3237
}: IProps) => {
3338
const [isChecked, handleCheck] = useState(checked);
3439

40+
useEffect(() => {
41+
changed(isChecked);
42+
}, [isChecked]);
43+
3544
const handleContainerClick = (e) => {
3645
e.preventDefault();
3746
if (!disabled && !labelDisabled) {
3847
handleCheck(!isChecked);
48+
clicked(e);
3949
}
4050
};
4151

4252
const handleIconClick = (e) => {
4353
e.preventDefault();
4454
if (!disabled) {
4555
handleCheck(!isChecked);
56+
clicked(e);
4657
}
4758
};
4859

60+
const iconName = isChecked ? activeIcon : inactiveIcon;
61+
const iconColor = disabled ? '#c8c9cc' : checkedColor;
62+
4963
return (
5064
<div
5165
className={classnames(baseClass, [
@@ -56,11 +70,7 @@ const Checkbox = ({
5670
onClick={handleContainerClick}
5771
>
5872
<div className={`${baseClass}__icon-container`} onClick={handleIconClick}>
59-
<Icon
60-
color={disabled ? '#c8c9cc' : checkedColor}
61-
name={isChecked ? activeIcon : inactiveIcon}
62-
size='20px'
63-
/>
73+
<Icon color={iconColor} name={iconName} size='20px' />
6474
</div>
6575
<label htmlFor={name}>{labelText}</label>
6676
</div>

0 commit comments

Comments
 (0)